【发布时间】:2012-01-20 04:18:58
【问题描述】:
在 windows phone 7 中,更新独立存储文本文件的协议是什么?假设我在一个文本文件中有 10 个单词,每行 1 个单词。现在假设,用户使用应用程序并且需要在第五行存储一个新单词。如何写入已经包含 10 个单词且每行 1 个单词的文件?
提前谢谢你们太棒了。
【问题讨论】:
标签: windows-phone-7 insert isolatedstorage text-files
在 windows phone 7 中,更新独立存储文本文件的协议是什么?假设我在一个文本文件中有 10 个单词,每行 1 个单词。现在假设,用户使用应用程序并且需要在第五行存储一个新单词。如何写入已经包含 10 个单词且每行 1 个单词的文件?
提前谢谢你们太棒了。
【问题讨论】:
标签: windows-phone-7 insert isolatedstorage text-files
我一直这样做的方式是:
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);
【讨论】:
在独立存储中写入文件基本上是文件写入操作。它类似于您在普通操作系统中访问普通文件并对其进行读写的方式。在您的场景中,如果您确定需要更新 10 行中的第 5 行,您将使用流阅读器逐行读取,并使用流编写器更新您要更新的特定行。您无需一次又一次地重写所有内容。
另一方面,如果您只想添加新内容,您可以将其附加到文件末尾。您可能会发现此链接很有用http://goo.gl/IKii5
【讨论】: