如何将字节数组转换回文件并使用C#自动打开?

我正在编写一些代码来将文件附件添加到我正在构建的应用程序中。

我有添加和删除工作,但我不知道从哪里开始实现打开。

我有一个字节数组(来自表字段),我不知道如何让它自动打开,例如

如果我有一个PDF格式的字节数组,如何让我的应用程序自动打开Acrobat或当前分配的扩展程序使用C#的任何应用程序?

要在任何外部应用程序中打开它,您需要将字节写入磁盘,然后使用Process.Start在临时文件上启动关联的应用程序。 只需传递临时文件名(带有相应的扩展名)作为Process.Start的唯一参数,它将在相应的应用程序中打开该文件。

某些应用程序可能有一种方法来提供字节流,但这需要由目标应用程序显式处理。


对于示例代码,您可以执行以下操作:

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); 

这可能会有所帮助

  byte[] bytes = File.ReadAllBytes(@"C:\temp\file.pdf"); string outpath = @"c:\temp\openme.pdf"; File.WriteAllBytes(outpath, bytes); Process.Start(outpath); 

只需将byte []写入磁盘,然后使用关联的应用程序运行它。

将数据写入临时文件并使用Process打开它。 这将使用为文件类型配置的标准程序。 (例如txt>记事本)

  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);