【问题标题】:windows phone 7 updating isolated storagewindows phone 7 更新隔离存储
【发布时间】:2012-01-20 04:18:58
【问题描述】:

在 windows phone 7 中,更新独立存储文本文件的协议是什么?假设我在一个文本文件中有 10 个单词,每行 1 个单词。现在假设,用户使用应用程序并且需要在第五行存储一个新单词。如何写入已经包含 10 个单词且每行 1 个单词的文件?

提前谢谢你们太棒了。

【问题讨论】:

    标签: windows-phone-7 insert isolatedstorage text-files


    【解决方案1】:

    我一直这样做的方式是:

    1. 将文件从IsolatedStorage 读入menmory
    2. 更新字符串
    3. 将文件写回存储

    读入文件

    public static string ReadFromStorage(string filename)
    {
        string fileText = "";
        try
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (StreamReader sr = new StreamReader(new IsolatedStorageFileStream(filename, FileMode.Open, storage)))
                {
                    fileText = sr.ReadToEnd();
                }
            }
        }
    
        catch
        {
        }
    
        return fileText;
    }
    

    写入文件

    public static void WriteToStorage(string filename, string text)
    {
        try
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string directory = Path.GetDirectoryName(filename);
                if (!storage.DirectoryExists(directory))
                    storage.CreateDirectory(directory);
    
                if (storage.FileExists(filename))
                {
                    MessageBoxResult result = MessageBox.Show(filename + " Exists\nOverwrite Existing File?", "Question", MessageBoxButton.OKCancel);
    
                    if (result == MessageBoxResult.Cancel)
                        return;
                }
    
                using (StreamWriter sw = new StreamWriter(storage.CreateFile(filename)))
                {
                    sw.Write(text);
                }
            }
        }
    
        catch
        {
        }
    }
    

    所以我会这样做:

    string fileName = "Test.txt";
    string testFile = IsolatedStorage_Utility.ReadFromStorage(fileName);
    testFile = testFile.Replace("a", "b");
    IsolatedStorage_Utility.WriteToStorage(fileName, testFile);
    

    【讨论】:

    • 所以基本上,你每次都覆盖文件?
    • 这更容易。这就是您在几乎任何操作系统上执行此操作的方式。想想窗户;你读入一个文件,修改它,然后重写整个东西。从技术上讲,如果您事先知道要更换什么,您可以只修改您需要的部件。我还假设您的文件相对较小并且您没有节省太多时间。
    【解决方案2】:

    在独立存储中写入文件基本上是文件写入操作。它类似于您在普通操作系统中访问普通文件并对其进行读写的方式。在您的场景中,如果您确定需要更新 10 行中的第 5 行,您将使用流阅读器逐行读取,并使用流编写器更新您要更新的特定行。您无需一次又一次地重写所有内容。

    另一方面,如果您只想添加新内容,您可以将其附加到文件末尾。您可能会发现此链接很有用http://goo.gl/IKii5

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多