[英]How do I turn an array of bytes back into a file and open it automatically with 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.