开发者

How do I turn an array of bytes back into a file and open it automatically with C#?

I am writing some code to add file attachments into an application I am building.

I have add & Remove working b开发者_开发百科ut I don't know where to start to implement open.

I have an array of bytes (from a table field) and I don't know how to make it automatically open e.g.

If I have an array of bytes which is a PDF, how do I get my app to automatically open Acrobat or whatever the currently assigned application for the extension is using C#?


In order to open it in any external application, you'll need to write the bytes to disk, then use Process.Start to launch the associated application on the temporary file. Just pass the temporary filename (with the appropriate extension) as the only argument the Process.Start, and it will open that file in the appropriate application.

Some applications may have a way to feed a stream of bytes, but this would need to be handled by the target application explicitly.


For sample code, you could do something like:

byte[] filedata = GetMyByteArray();
string extension = GetTheExtension(); // "pdf", etc

string filename =System.IO.Path.GetTempFileName() + "." + extension; // Makes something like "C:\Temp\blah.tmp.pdf"

File.WriteAllBytes(filename, filedata);

var process = Process.Start(filename);
// Clean up our temporary file...
process.Exited += (s,e) => System.IO.File.Delete(filename); 


This may help a bit

        byte[] bytes = File.ReadAllBytes(@"C:\temp\file.pdf");

        string outpath = @"c:\temp\openme.pdf";
        File.WriteAllBytes(outpath, bytes);
        Process.Start(outpath);

Simply writes the byte[] to disk and then runs it with the associated application.


Write the data to a temporary file and open it using Process. This will use the standard programm configured for the filetype. (eg txt > notepad)

        byte[] b = new byte[]{0x0};
        var fileName = "c:\\test.txt";
        System.IO.File.WriteAllBytes(fileName, b);
        System.Diagnostics.Process.Start(fileName);


// get the PDF in byte form from the system
var bytes = GetFileBytes("Some identifier");
// get a valid temporary file name and change the extension to PDF
var tempFileName = Path.ChangeExtension(Path.GetTempFileName(), "PDF");
// write the bytes of the PDF to the temp file
File.WriteAllBytes(tempFileName, bytes);
// Ask the system to handle opening of this file
Process.Start(tempFileName);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜