我正在使用Windows phone7中的C#覆盖一个文件。当我这样做的时候,一个看似随机的字符被添加到了每一行的开头。
为什么会发生这种情况?
代码:
public static bool overwriteFile(string filename, string[] inputArray)
{
try
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
FileStream stream = store.OpenFile(filename, FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
foreach (string input in inputArray)
{
writer.Write(input + "\n");
}
writer.Close();
return true;
}
catch (IOException ex)
{
return false;
}
}Lodaing代码:
public static Idea[] getFile(string filename)
{
try
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
string fileContents = null;
if (store.FileExists(filename)) // Check if file exists
{
IsolatedStorageFileStream save = new IsolatedStorageFileStream(filename, FileMode.Open, store);
StreamReader streamReader = new StreamReader(save);
fileContents = streamReader.ReadToEnd();
save.Close();
}
string[] lines = null;
if (fileContents != null)
{
lines = fileContents.Split('\n');
}
Idea[] ideaList = null;
if (lines != null)
{
ideaList = new Idea[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
ideaList[i] = new Idea(lines[i].TrimEnd('\r'));
}
}
return ideaList;
}
catch (IOException ex)
{
return null;
}
}发布于 2011-07-05 06:07:08
随机字符是一个长度前缀;请参阅http://msdn.microsoft.com/en-us/library/yzxa6408.aspx。
您应该使用某种类型的TextWriter将字符串写入文件,而不是使用BinaryWriter。
StreamWriter可能是最好的,然后您可以使用WriteLine方法。
发布于 2011-07-05 05:58:09
尝试使用Environment.NewLine,而不是使用'\n'
发布于 2011-07-05 06:07:23
您正在使用BinaryWriter进行写入,使用TextReader进行读取。将您的代码更改为使用StreamWriter (这是一个TextWriter)而不是BinaryWriter。这也会让你得到纳维德推荐的WriteLine方法。
https://stackoverflow.com/questions/6576357
复制相似问题