【问题标题】:Is there a better way than this to find out if an IsolatedStorage file exists or not?有没有比这更好的方法来确定一个独立存储文件是否存在?
【发布时间】:2010-04-14 19:20:15
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# silverlight isolatedstorage


    【解决方案1】:

    来自《手册》(.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
    {
        // ...
    
    } 
    

    【讨论】:

    • 感谢帮助我弄清楚我错过了什么,实际上,事实证明,您可以使用 userStore.FileExists() (Silverlight 3)
    • 很好的观察,你确实有一个 IsolatedStorageFile.FileExists() 方法,但仅限于 .net 4(我还没有使用 4.0)。对于早期版本,您可以使用上面的示例。
    • 在我当前的机器上我只安装了 3.5 并且 IsolatedSTorageFile.FileExists() 工作
    • 我有 3.5,但我没有 FileExists 方法...(在 msdn 上,IsolatedStorageFile.FileExits 支持的框架也是 4.0)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多