R
R
Rustam2011-07-21 11:45:39
C++ / C#
Rustam, 2011-07-21 11:45:39

File.WriteAllBytes vs BinaryWriter?

There are several ways to write binary data to a file. One of them
File.WriteAllBytes (path, buffer);, the
other

BinaryWriter writer = new BinaryWriter (File.OpenWrite (path));<br/>
 writer.Write (buffer);<br/>
 writer.Flush ();

Offhand, the first way looks nicer (in terms of readability), but which one is faster?
And how do both methods work?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PashaPash, 2011-07-21
@Rustam

The first one opens a FileStream inside and writes bytes from the buffer into it. WriteAllBytes writes bytes to the stream with this line:
fs.Write(bytes, 0, bytes.Length);
Second, you yourself open a FileStream, for some reason you wrap it in a BinaryWriter. BinaryWriter writes to FileStream something like this:
OutStream.Write(buffer, 0, buffer.Length);
No difference. Only the first method closes the file. And the second one is not, it lacks a call to Dispose.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question