Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file from Memory Stream

Is it possible to open a file directly from a MemoryStream opposed to writing to disk and doing Process.Start() ? Specifically a pdf file? If not, I guess I need to write the MemoryStream to disk (which is kind of annoying). Could someone then point me to a resource about how to write a MemoryStream to Disk?

like image 861
James Avatar asked Jun 04 '11 11:06

James


People also ask

How does memory stream work?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.

How do I convert files to stream?

First create FileStream to open a file for reading. Then call FileStream. Read in a loop until the whole file is read. Finally close the stream.

Do I need to close memory stream?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .


2 Answers

It depends on the client :) if the client will accept input from stdin you could push the dta to the client. Another possibility might be to write a named-pipes server or a socket-server - not trivial, but it may work.

However, the simplest option is to just grab a temp file and write to that (and delete afterwards).

var file = Path.GetTempFileName();
using(var fileStream = File.OpenWrite(file))
{
    var buffer = memStream.GetBuffer();
    fileStream.Write(buffer, 0, (int)memStream.Length);
}

Remember to clean up the file when you are done.

like image 60
Marc Gravell Avatar answered Sep 18 '22 15:09

Marc Gravell


Path.GetTempFileName() returns file name with '.tmp' extension, therefore you cant't use Process.Start() that needs windows file association via extension.

like image 23
Kakha Middle Or Avatar answered Sep 22 '22 15:09

Kakha Middle Or