5

While making a lab on window 8 app dev. I could not load all images needed. So inorder for the share part to work with a sharing imag I need to check if the image file is availeble. The project is a windows grid app using XAML and C# In the past I used

Using System.IO
 ... lost of code
privat void share()
....
    if (File.exist(filename)
    { 
       add file to share
    }

If i try this in my window8 project. The File class is not found.

I search the internet but could not find a code example that checkes the existance in a windowsstore app in C#

Michiel

Mayank
  • 8,777
  • 4
  • 35
  • 60

2 Answers2

13

you need StorageFile not File

here is simple example to check and get the file

StorageFile file;
try {
    file = await ApplicationData.Current.LocalFolder.GetFileAsync("foo.txt");
}
catch (FileNotFoundException) {
    file = null;
}

you can write a function

public static async Task<bool> FileExistsAsync(this StorageFolder folder, string fileName)
{
    try
    {
        await folder.GetFileAsync(fileName);
        return true;
    }
    catch (FileNotFoundException)
    {
        return false;
    }
}
Mayank
  • 8,777
  • 4
  • 35
  • 60
  • It appears that it should be "[StorageFolder](http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.storagefolder)" instead of "LocalStorage" -- is that a change in the API since this was answered, or simply my own misunderstanding? – Dawson Toth Jun 30 '13 at 15:07
  • Have to be some api change or some misunderstanding on your part as code above worked fine. – Mayank Jun 30 '13 at 17:57
  • 1
    @DawsonToth I guess they changed the api and now instead of `LocalStorage` it's `LocalFolder` – Mayank Jun 30 '13 at 18:08
  • 2
    In Windows 8.1, you can avoid the (slow) exception-handling by using the new method: [TryGetItemAsync()](http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.storagefolder.trygetitemasync.aspx). – skst Jun 14 '14 at 21:14
2

If you know the path in your local storage and you have a bunch of files to check, you can do the following...

var sourceFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
sourceFolder = await sourceFolder.GetFolderAsync("Assets");
var files = await sourceFolder.GetFilesAsync();
var requiredFiles = new List<String> { "ThisWorks.png", "NotHere.png" };
foreach(var filename in requiredFiles)
{
    // your example logic here...
    Debug.WriteLine(filename + " " + (files.Any(f => f.Name == filename) ? "Exists" : "Doesn't exist"));
}
ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
  • Of course, `Windows.ApplicationModel.Package.Current.InstalledLocation` can be replaced with the relevant reference to the folder you care about. – ZombieSheep Nov 26 '12 at 18:08