简体   繁体   中英

Open file from byte array

I am storing attachments in my applications.

These gets stored in SQL as varbinary types.

I then read them into byte[] object.

I now need to open these files but dont want to first write the files to disk and then open using Process.Start() .

I would like to open using inmemory streams . Is there a way to to this in .net. Please note these files can be of any type

You can write all bytes to file without using Streams:

System.IO.File.WriteAllBytes(path, bytes);

And then just use

Process.Start(path);

Trying to open file from memory isn't worth the result. Really, you don't want to do it.

MemoryStream has a constructor that takes a Byte array .

So:

var bytes = GetBytesFromDatabase(); // assuming you can do that yourself
var stream = new MemoryStream(bytes);

// use the stream just like a FileStream

That should pretty much do the trick.

Edit: Aw, crap, I totally missed the Process.Start part. I'm rewriting...

Edit 2:

You cannot do what you want to do. You must execute a process from a file . You'll have to write to disk; alternatively, the answer to this question has a very complex suggestion that might work, but would probably not be worth the effort.

My only issue with this was that I will have to make sure the user has write access to the path where I will place the file...

You should be able to guarantee that the return of Path.GetTempFileName is something to which your user has access.

...and also am not sure how I will detect that the user has closed the file so I can delete the file from disk.

If you start the process with Process.Start(...) , shouldn't you be able to monitor for when the process terminates?

If you absolutely don't want to write to disk yourself you can implement local HTTP server and serve attachemnts over HTTP (like http://localhost:3456/myrecord123/attachment1234.pdf ). Also I'm not sure if you get enough benefits doing such non-trivial work. You'll open files from local security zone that is slightly better then opening from disk... and no need to write to disk yourself. And you'll likely get somewhat reasonable warning if you have .exe file as attachment.

On tracking "process done with the attachment" you more or less out of luck: only in some cases the process that started openeing the file is the one that is actually using it. Ie Office applications are usually one-instance applications, and as result document will be open in first instance of the application, not the one you've started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM