可能重复:
Why does BinaryWriter prepend gibberish to the start of a stream? How do you avoid it?
public static void saveFile(string path, string data)
{
using (Stream fileStream = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.None))
{
using (BinaryWriter bw = new BinaryWriter(fileStream))
{
bw.Write(data);
}
}
}
但是,每次调用该方法时,它都会在写入之前添加以下2个字符:alt text http://i45.tinypic.com/smxc3d.png。如果它有任何区别,我将它保存为.txt。此外,字符串在跟踪输出上显示正常。我该如何解决这个问题?
答案 0 :(得分:3)
BinaryWriter.Write(string)
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.write.aspx - 在BinaryWriter的当前编码中将长度前缀字符串写入此流,并根据以下内容推进流的当前位置使用的编码和写入流的特定字符。
答案 1 :(得分:0)
如果要将字符串保存为纯文本文件,请使用StreamWriter而不是BinaryWriter:
public static void saveFile(string path, string data)
{
using (Stream fileStream = File.Open(path, FileMode.Append, FileAccess.Write, FileShare.None))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.Write(data);
}
}
}