How to open a file from Memory Stream

浪尽此生 提交于 2019-12-10 13:53:53

问题


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?


回答1:


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.




回答2:


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




回答3:


If by opening a file, you mean something like starting Adobe Reader for PDF files, then yes, you have to write it to a file. That is, unless the application provides you with some API do that.

One way to write a stream to file would be:

using (var memoryStream = /* create the memory stream */)
using (var fileStream = File.OpenWrite(fileName))
{
    memoryStream.WriteTo(fileStream);
}


来源:https://stackoverflow.com/questions/6236602/how-to-open-a-file-from-memory-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!