Reputation: 3135
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
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