UWP Check If File Exists
Solution 1
public async Task<bool> IsFilePresent(string fileName)
{
var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
return item != null;
}
But not support Win8/WP8.1
Solution 2
There are two methods
1) You can use StorageFolder.GetFileAsync()
as this is also supported by Windows 8.1 and WP 8.1 devices.
try
{
StorageFile file = await DownloadsFolder.GetFileAsync("01-Introduction.pdf");
}
catch
{
Debug.WriteLine("File does not exits");
}
2) Or you can use FileInfo.Exists
only supported for windows 10 UWP.
FileInfo fInfo = new FileInfo("01-Introduction.pdf");
if (!fInfo.Exists)
{
Debug.WriteLine("File does not exits");
}
Solution 3
System.IO.File.Exists is UWP way too. I test now in Windows IOT. it just works.
Solution 4
This helped me in my case:
ApplicationData.Current.LocalFolder.GetFileAsync(path).AsTask().ContinueWith(item => {
if (item.IsFaulted)
return; // file not found
else { /* process file here */ }
});
Solution 5
This worked for me running my UWP C# app on Windows 10...
StorageFolder app_StorageFolder = await StorageFolder.GetFolderFromPathAsync( @App.STORAGE_FOLDER_PATH );
var item = await app_StorageFolder.TryGetItemAsync(relative_file_pathname);
return item != null;
Related videos on Youtube
James Tordoff
C# Apprentice at Galleos, Based in Leeds, West Yorkshire.
Updated on July 09, 2022Comments
-
James Tordoff almost 2 years
I am currently working on a Windows 10 UWP App. The App needs to Check if a certain PDF File exists called "01-introduction", and if so open it. I already have the code for if the file does not exist. The Code Below is what i currently have:
try { var test = await DownloadsFolder.CreateFileAsync("01-Introduction.pdf", CreationCollisionOption.FailIfExists); } catch { }
This code Does not work correctly because to check if the file exists here, I attempt to create the file. However if the file does not already exist an empty file will be created. I do not want to create anything if the file does not exist, just open the PDF if it does.
If possible, i would like to look inside a folder which is in the downloads folder called "My Manuals".
Any help would be greatly appreciated.
-
Jay Zuo about 8 yearsIs the "Swift Manuals" folder created by your app? By default, your app can only access files and folders in the user's Downloads folder that your app created. However, you can gain access to files and folders in the user's Downloads folder by calling a file picker (FileOpenPicker or FolderPicker) so that users can navigate and pick files or folders for your app to access.
-
James Tordoff about 8 years@JayZuo-MSFT Thank you for the clarification Jay. This is the problem we have been coming across. So we can get directory access to Downloads. We need to look at another approach and do a little more reading.
-
Jay Zuo about 8 yearsIf you create a file or folder in the Downloads folder, we recommend that you add that item to your app's FutureAccessList so that your app can readily access that item in the future. For more info, please see File access permissions.
-
-
James Tordoff about 8 yearsUnfortunately (1) does not seem available within Windows 10 UWP there is no Definition ofr GetFileAsync for DownloadsFolder. (2) seems to be just what I am looking for, unfortunately I always return False, how do I specify which folder is to be searched for the FileInfo. I am only supporting Win10 and not backwards compatible at all.
-
James Tordoff about 8 yearsThanks Ben, both you and Absolute have hit in the right direction, but unfortunately I am currently only returning False, I have commented above with Absolute, how can I confirm which Directory/Folder is being searched for the FileInfo ?
-
AbsoluteSith about 8 yearsAre you sure DownloadFolder is a StorageFolder type, if so it should have a definition. Try pasting your entire code, I'll check it out
-
Archana about 8 yearsDownloadFolder doesnt have GetFileAsync () method
-
Ben Steele about 8 yearsI think you may need to use the getfile functions to see if they return an object or null. Answer updated
-
Peter Torr - MSFT over 7 yearsThat is not the Downloads folder.
-
Reynevan over 6 yearsIt will throw an exception when the item is not found.
-
lindexi over 6 years@Reynevan It doesn't throw an exception.
-
CBHacking over 6 yearsIf you're going to use
System.IO
at all, you might as well useSystem.IO.File.Exists(String)
. It's more efficient - no need to construct an object - and simpler to read. -
CBHacking over 6 yearsWhile not "the UWP way" (in particular, it does an I/O operation - albeit a very fast one - synchronously), this is a viable option on UWP (Win10) apps. Just be aware that the app will not have any kind of lock on the file; if another thread or process removes or creates the file between check and use, you could get unexpected (and potentially harmful) behavior.
-
DirtyNative about 6 yearsIndeed, it does not throw any Exception, altought the Docs say they do
-
visc almost 6 yearsThis fails on files when paths are too long: stackoverflow.com/questions/11210408/…
-
Wagner Bertolini Junior almost 6 years@visc on the Thread you an see on a comment that this method is expected to return false when any errors occurs when trying to reach file. So, if the system treats "path to long" as an error, this method is still right. The solution presented on the other thread is inefficient as the author confirms, I tried here to present the most "elegant" solution. And it works on 99.9% of times, so I don´t think its useful to integrate that solution on this proposal.
-
Filipe Madureira over 4 yearsThis is not the downloads folder but the local app folder which gets overwritten between deployments and updates, beware.
-
Weissu about 3 yearsHave to remember that TryGetItemAsync returns Files AND Folders. Need to check type of returned item like item.IsOfType(StorageItemTypes.File).
-
Alamakanambra over 2 yearsThis is the best solution, since you don't have to catch any exception here and it works with
StorageFolder
class. -
Sean O'Neil about 2 years@CBHacking This is actually not true. It only works in the app's LocalFolder (and probably LocalCache and Temp). Even if you have access to another folder using the picker or a capability, System.IO stuff won't work there.
-
Sean O'Neil about 2 yearsNo, it only works in LocalFolder, LocalCache, etc. Even if you grant access to another folder/file using the picker, or use a special folder (like Downloads in the question) the System.IO methods won't work there.
-
CBHacking about 2 years@SeanO'Neil That's false for a few reasons. First, you can absolutely use
System.IO.File
to access files outside the app storage, such as in the system directory or, with the right capabilities defined, locations such as removable storage. Second, you can test for existence of files you can't even access; you'll get a different error for "file not found" vs. "access denied". Third, even if if checking app-specific files, an appcontainer can have multiple processes (e.g. background audio process) and any process can have multiple threads, so you do risk TOCTOU bugs. -
CBHacking about 2 years... Well. At some point they decided to make Access Denied errors return false for
File.Exists()
, which is a lie. You CAN still (I just checked) try to open or stat the file (File.GetFileAttributes()
works even if you don't have read permissions; so does opening the file without requesting any access but you can't do that usingSystem.IO.File
). That will either work or throw an exception; FileNotFound or DirectoryNotFound mean the file doesn't exist, UnauthorizedAccess means it does. -
Sean O'Neil about 2 years@CBHacking Yeah File.Exists, EnumerateFiles, etc. hasn't worked as long as I remember. Perhaps as you say it used to. I forgot to mention it does, however, work on exFAT file systems, just not on NTFS.
-
Sean O'Neil about 2 yearsNever tried GetFileAttributes, it would be interesting to see if that's faster than the Windows.Storage way of doing it.