Is there any other way of checking whether a file exists in a Windows Store app?
try
{
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(
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
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
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.
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
I tried to write my own using old tricks:
All in all -- you're better of sticking with exception handling method.
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