代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

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

  •  3
  • Edward Tanguay  · 技术社区  · 15 年前

    我在用 隔离存储器 在一个 银光 用于缓存的应用程序,因此我需要知道文件是否存在,我使用以下方法进行处理。

    我找不到 否存在 IsolatedStorage的方法,因此我只捕获异常,但它似乎是 一般例外 ,我担心如果文件不存在,它会捕获更多。

    是否有比以下更好的方法来查明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 "";
            }
        }
    }
    
    1 回复  |  直到 15 年前
        1
  •  4
  •   Ando SylviA    15 年前

    从“手册”(.NETFramework 2应用程序开发基金会):

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

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