Raghav55
Raghav55

Reputation: 3135

why such a difference in file contents C#

My intention is to write a byte[] to a file. Code snippet is below:

byte[] stream = { 10, 20, 30, 40, 60 };

for (int i = 0; i < 2; i++)
{
    FileStream aCmdFileStream = new FileStream(@"c:\binarydata.txt", FileMode.Append, FileAccess.Write, FileShare.None);
    StreamWriter aStreamWriter = new StreamWriter(aCmdFileStream);

    for (int ii = 0; ii < stream.Length; ii++)
    {
        aStreamWriter.Write(stream[ii]);
        aStreamWriter.WriteLine(); 
        aStreamWriter.BaseStream.Write(stream,0,stream.Length);
    }

    aStreamWriter.Close();
}

Output of this code snippet

(<
(<
(<
(<
(<10
20
30
40
60

(<
(<
(<
(<
(<10
20
30
40
60

When StreamWriter.Write() is used it dumps the values which are stored in array. But StreamWriter.BaseStream.Write(byte[],int offset, int length), the values are totally different. What is the reason for this?

Upvotes: 1

Views: 161

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273219

This is because StreamWriter is a TextWriter and converts the bytes to Text (string representation).

And using BaseStream.Write(byte[] data, ...) directly writes the bytes without any conversion.

But you are using the 2 methods interleaved, I guess some overwriting is happening too. Note that you should use one or the other, not both.

Upvotes: 4

Related Questions