Hi Friends,

I recently came across a requirement to check if a file is present in the local storage of WinRT application as well as Windows phone 8 application.

I did not find any suitable methods available in the LocalFolder class such as  LocalFolder.FileExists().  I searched over the internet and what most people suggested are as below.

  1. Handle Exception Method
  2. Looping over all file names to check if the name exists.
1. Handling exception method:
 public async Task<bool> isFilePresent(string fileName)
{
bool fileExists = true;
Stream fileStream = null;
StorageFile file = null;

try
{
file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
fileStream = await file.OpenStreamForReadAsync();
fileStream.Dispose();
}
catch (FileNotFoundException)
{
// If the file dosn't exits it throws an exception, make fileExists false in this case
fileExists = false;
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}

return fileExists;
}

2. Looping over all file names to check if the name exists


public async Task<bool> isFilePresent(string fileName)
{
bool fileExists = false;
var allfiles = await ApplicationData.Current.LocalFolder.GetFilesAsync();
foreach (var storageFile in allfiles)
{
if (storageFile.Name == fileName)
{
fileExists = true;
}
}
return fileExists;
}

Both seem to be costly operations and handling exception is not the right way.

 

Solution :

The Solution is a little different from WinRT to WP8.

WP8 Solution

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

 

WinRT Solution :

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

 

Feel free to comment and Rate the articles. 

Thanks Friends!!!!!!!!!! 

Happy Coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!