3

我在Silverlight应用程序中使用IsolatedStorage进行缓存,因此我需要知道文件是否存在,我使用以下方法执行此操作。

我找不到用于 IsolatedStorage 的FileExists方法,所以我只是在捕获异常,但这似乎是一个非常普遍的异常,我担心它会比文件不存在时捕获更多。

有没有比这更好的方法来确定隔离存储中是否存在文件:

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 "";
        }
    }
}
4

1 回答 1

4

来自“手册”(.net framework 2.0 Application Development Foundation):

与文件系统中任意存储文件的应用程序编程接口 (API) 不同,独立存储中文件的 API 不支持直接检查文件是否存在File.Exists。相反,您需要向商店询问与特定文件掩码匹配的文件列表。如果找到,则可以打开文件,如本例所示

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

} 
于 2010-04-14T11:20:15.357 回答