MemoryStream.SaveToFile

A

Alexander Muylaert

Hi

What would be the easiest way to save a memorystream to a file?

Kind regards

Alexander
 
T

Tamir Khason

Convert it to binary filestream or just write byte ofter byte.
If you need an example there are about 20 in MSDN
 
J

Jon Skeet [C# MVP]

Alexander Muylaert said:
What would be the easiest way to save a memorystream to a file?

Well, the *easiest* way would be to open a file stream and then use:

byte[] data = memoryStream.ToArray();
fileStream.Write(data, 0, data.Length);

That's relatively inefficient though, as it involves copying the
buffer. It's fine for small streams, but for huge amounts of data you
should consider using:

fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position);

(assuming the memory stream is already positioned at the end).
 
J

John Wood

// ms is your memoryStream
FileStream fs = File.OpenWrite("blah.dat");


/* could replace with GetBuffer() if you don't mind the padding, or you
could set Capacity of ms to Position to crop the padding out of the
buffer.*/
fs.Write(ms.ToArray());

fs.Close();
 
J

Jon Skeet [C# MVP]

Tamir Khason said:
Convert it to binary filestream or just write byte ofter byte.
If you need an example there are about 20 in MSDN

Writing individual bytes is likely to be very much slower than writing
the whole buffer in one go.

Not sure what you meant by "convert it to binary filestream" to be
honest...
 
A

Alexander Muylaert

Hi guys

Are you seriously telling me that there is no way I can write the internall
array fast to a file?
No optimized routine that writes a memorystream in blocks to a file?

In Delphi you have TMemorystream.SaveToFile.
This actually writes the memorystream to file, optimized for disk
performance. (blocks of 8 k etc..)

Kind regards

Alexander
 
J

John Wood

I don't understand what the problem is.

The code:

FileStream fs = File.OpenWrite("blah.dat");
fs.Write(ms.GetBuffer(), 0, ms.Position);
fs.Close();

Is pretty damn fast, and short. Any write-based optimizations will be taken
care of by the FileStream implementation and shouldn't be something you have
to worry about.

I think, from a design point of view, it would be wrong to have a SaveToFile
function in the MemoryStream object. The purpose of the MemoryStream is just
that, to provide a stream interface onto a block of memory. The FileStream
writes to files, and so it makes sense to use a FileStream to dump out the
internal buffer of the MemoryStream (which is what GetBuffer() provides) to
a file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top