views:

69

answers:

1

I'm using IsolatedStorage in a Silverlight application for caching, so I need to know if the file exists or not which I do with the following method.

I couldn't find a FileExists method for IsolatedStorage so I'm just catching the exception, but it seems to be a quite general exception, I'm concerned it will catch more than if the file doesn't exist.

Is there a better way to find out if a file exists in IsolatedStorage than this:

public static string LoadTextFromIsolatedStorageFile(string fileName)
{
    string text = String.Empty;

    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        try
        {
            using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName,
                            FileMode.Open, isf))
            {
                using (StreamReader sr = new StreamReader(isfs))
                {
                    string lineOfData = String.Empty;
                    while ((lineOfData = sr.ReadLine()) != null)
                        text += lineOfData;
                }
            }
            return text;
        }
        catch (IsolatedStorageException ex)
        {
            return "";
        }
    }
}
+2  A: 

From the "manual" (.net framework 2.0 Application Development Foundation):

Unlike the application programming interface (API) for files stored arbitrarily in the file system, the API for files in Isolated Storage does not support checking for the existence of a file directly like File.Exists does. Instead, you need to ask the store for a list of files that match a particular file mask. If it is found, you can open the file, as shown in this example

string[] files = userStore.GetFileNames("UserSettings.set");
if (files.Length == 0)
{
Console.WriteLine("File not found");
}
else
{
    // ...

} 
Ando
thanks that helped me figure out what I was missing, actually, as it turns out, you can use userStore.FileExists() (Silverlight 3)
Edward Tanguay
Good observation, you do have an IsolatedStorageFile.FileExists() method, but only in .net 4 (I'm not working with 4.0 yet). For earlier versions you can use the example above.
Ando
on my current machine I only have 3.5 installed and IsolatedSTorageFile.FileExists() works
Edward Tanguay
I have 3.5 and I don't have the FileExists method ... (also on msdn the supported framework for IsolatedStorageFile.FileExits is 4.0)
Ando