开发者

C#: 2 unwanted additional characters are being appended during file write [duplicate]

This question already has answers here: 开发者_JAVA技巧 Closed 12 years ago.

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:

C#: 2 unwanted additional characters are being appended during file write [duplicate]

. 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);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜