C#: 2 unwanted additional characters are being appended during file write [duplicate]
Possible Duplicate:
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);
}
}
}
However, everytime the method is called it adds the following 2 characters before writing:
. I'm saving it to a .txt if it makes any difference. Also, the string displays fine on the trace output. How do I fix this?BinaryWriter.Write(string)
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.write.aspx - Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter, and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream.
If you're saving a string to a plain text file, use a StreamWriter instead of the 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);
}
}
}
精彩评论