Abdul Samad
Abdul Samad

Reputation: 5918

converting MemoryStream array to fileStream C#

I have a function that is returning MemoryStream array, i want to convert this memory stream array to a FileStream object.

Is it possible if yes can you please provide a way to do that...

Thanks A.S

Upvotes: 1

Views: 2587

Answers (2)

Mike Dinescu
Mike Dinescu

Reputation: 55720

A file stream object represents an open file (from disk) as a stream. A memory stream represents an area of memory (byte array) as a stream. So you can't really convert a memory stream into a file stream directly - at least not trivially.

There are two approaches you could take:

  1. OFFLINE: fully consume the contents of the memory stream and write it all out to a file on disk; then open that file as a file stream

  2. ONLINE: extent the FileStream class creating an adapter that will wrap a MemoryStream object and expose it as a FileStream (essentially acting as a converter)

The reason one is marked [OFFLINE] is because you need to have to full contents of the memory stream before you output it to the file (and once you do, modifications to the file stream will not affect the memory stream; nor changes to the memory stream, such as new data, be available to the file stream)

The second one is marked as [ONLINE] because once you create the adapter and you initialize the FileStream object from the MemoryStream you could process any new data in the MemoryStream using the FileStream adapter object. You would essentially be able to read/write and seek into the memory stream using the file stream as a layer on top of the memory stream. Presumably, that's what you'd want to do..

Of course, it depends on what you need to do, but I'm leaning towards the second [ONLINE] version as the better in the general sense.

Upvotes: 0

Anders Marzi Tornblad
Anders Marzi Tornblad

Reputation: 19305

You cannot "convert" the stream, because a MemoryStream and a FileStream are very different things. However, you can write the entire contents of the MemoryStream to a file. There is a CopyTo method that you can use for that:

// memStream is the MemoryStream
using (var output = File.Create(filename)) {
    memStream.CopyTo(output);
}

Upvotes: 2

Related Questions