How to check if file exists in a Windows Store App?
Asked Answered
D

10

48

Is there any other way of checking whether a file exists in a Windows Store app?

try
{
    var file = await ApplicationData.Current.LocalFolder.GetFileAsync("Test.xml");
    //no exception means file exists
}
catch (FileNotFoundException ex)
{ 
    //find out through exception 
}
Disposal answered 24/12, 2011 at 17:51 Comment(0)
G
26

According to the accepted answer in this post, there is no other way at the moment. However, the File IO team is considering changing the the api so that it returns null instead of throwing an exception.

Quote from the linked post:

Currently the only way to check if a file exists is to catch the FileNotFoundException. As has been pointed out having an explicit check and the opening is a race condition and as such I don't expect there to be any file exists API's added. I believe the File IO team (I'm not on that team so I don't know for sure but this is what I've heard) is considering having this API return null instead of throwing if the file doesn't exist.

Gowk answered 24/12, 2011 at 17:57 Comment(4)
I believe that the new IsAvailable property in Windows 8.1 addresses this.Weisshorn
@Weisshorn - Thanks, that's good to know. I haven't had the chance to look into the 8.1 APIs yet.Gowk
ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName) can do the trick now. No more ugly exception handling required. Please remember that this is also an awaitable call.Apteral
Unfortunately, that call doesn't exist for Windows Phone, so you're out of luck if you're building a Universal App for Windows 8.1/Windows Phone 8.1. I guess I'll just have to retarget my app to Windows 10....Pemberton
S
13

This may be old, but it looks like they've changed how they want you to approach this.

You're supposed to attempt to make the file, then back down if the file already exists. Here is the documentation on it. I'm updating this because this was the first result on my Google search for this problem.

So, in my case I want to open a file, or create it if it doesn't exist. What I do is create a file, and open it if it already exists. Like so:

save = await dir.CreateFileAsync(myFile, CreationCollisionOption.OpenIfExists);
Sailesh answered 24/8, 2012 at 21:22 Comment(1)
This only works if you are trying to create file with a unique name. If you are just checking for existence of the file then obviously you wouldn't want to do this.Compagnie
U
8

I stumbled on to this blog post by Shashank Yerramilli which provides a much better answer.

I have tested this for windows phone 8 and it works. Haven't tested it on windows store though

I am copying the answer here

For windows RT app:

public async Task<bool> isFilePresent(string fileName)
 {
    var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
    return item != null;
 }

For Windows Phone 8

 public bool IsFilePresent(string fileName)
 {
     return System.IO.File.Exists(string.Format(@"{0}\{1}", ApplicationData.Current.LocalFolder.Path, fileName);
 }

Check if a file exists in Windows Phone 8 and WinRT without exception

Unpin answered 8/3, 2014 at 12:0 Comment(6)
"The type or namespace name 'File' does not exist in the namespace 'System.IO' (are you missing an assembly reference?)"Metalinguistic
What app type are you trying to use it in : Windows Phone 8, or Windows RT App?Unpin
A universal Windows / Phone store app that targets 8.1. Also, while you're here: your WP8 function should just return a bool, and it doesn't need the async keyword either.Metalinguistic
Thanks for letting me know about the correction, The 'File.Exists()' solution only works in Window phone 8. The 'localFolder.TryGetItem()' method will work in the Windows 8.1 part of the universal app. For windows phone 8.1 part: you can try the solution by Billdr https://mcmap.net/q/359238/-how-to-check-if-file-exists-in-a-windows-store-app.Unpin
The answer you linked to wouldn't work, as it returns a file whether it exists or not (because it creates it in the latter case).Metalinguistic
Its weird that they removed the File.Exists() from windows phone 8.1, I guess right now the only way is to try to open the file & catch an exception.Unpin
A
3

You can use the old Win32 call like this to test if directory exist or not:

GetFileAttributesExW(path, GetFileExInfoStandard, &info);

return (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? false: true;

It works in Desktop and Metro apps: http://msdn.microsoft.com/en-us/library/windows/desktop/aa364946%28v=vs.85%29.aspx

Apteryx answered 2/7, 2012 at 22:35 Comment(1)
Where does FILE_ATTRIBUTE_DIRECTORY come from here? I tested this function, and it works, but I don't see how. Thanks!Crites
W
3

Microsoft has added a new function to StorageFile in Windows 8.1 to allow user engineers to determine if a file can be accessed: IsAvailable

Weisshorn answered 4/9, 2013 at 17:54 Comment(1)
Not supported on Windows *Phone* 8.1, only Windows 8.1. I don't know what MS is playing at.Compass
J
2

The other means to check is by getting files in local folder

    var collection =  ApplicationData.Current.LocalFolder.GetFilesAsync() 

Using this method and then iterating over all the elements in the collection and check for its availability.

Jetport answered 6/9, 2012 at 10:12 Comment(1)
Please check your caps lock key.Duet
D
1

I tried to write my own using old tricks:

  1. GetFileAttributesEx() always seems to end up with ERROR_ACCESS_DENIED if file selected via FileOpenPicker;
  2. Ditto for FindFirstFileEx();
  3. _stat() always ends up with ENOENT when file selected via FileOpenPicker;
  4. CreateFile2() with CREATE_NEW option works -- if file does exist it will fail with INVALID_HANDLE_VALUE return value and ERROR_FILE_EXISTS last error; if file does not exist you have to remember to delete created file afterwards.

All in all -- you're better of sticking with exception handling method.

Dannydannye answered 7/6, 2012 at 1:43 Comment(0)
O
1

8.1 got something like this, I tried it worked.

var folder = ApplicationData.Current.LocalFolder;
var file = await folder.TryGetItemAsync("mytext.txt") as IStorageFile;

if (file == null)
{
   //do what you want
}
else
{
   //do what you want
}

http://marcominerva.wordpress.com/2013/11/19/how-to-check-if-a-file-exists-in-a-windows-8-1-store-apps-no-more-exception-handling/

Offense answered 27/11, 2014 at 7:31 Comment(1)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.Decadent
D
1
    Dim myPath As StorageFolder
    If (From i In Await KnownFolders.MusicLibrary.GetFoldersAsync() Where i.Name = "PodBong").Count = 1 Then
        myPath = Await KnownFolders.MusicLibrary.GetFolderAsync("PodBong")
    Else
        myPath = Await KnownFolders.MusicLibrary.CreateFolderAsync("PodBong")

    End If
Dannica answered 11/8, 2015 at 18:0 Comment(1)
This code will check for folder with out using and exception.Dannica
L
0

The documentation for TryGetItemAsync says, "This example shows how to checkfor the existence of a file." It seems that this API is officially intended to serve that purpose.

Leisha answered 9/5, 2014 at 16:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.