在 Windows 窗体应用程序中,我有一个文件存储为byte[]
.
当用户单击按钮时,我想打开文件而不将其保存在本地。这可能吗?如果是那怎么办?
或者我是否必须将字节数组保存为本地文件然后运行该文件?
谢谢,卡尔
如果您想在应用程序中打开(就像 Windows 双击具有适当扩展名的文件一样),您必须将其内容写入文件:
/// <summary>
/// Saves the contents of the <paramref name="data"/> array into a
/// file named <paramref name="filename"/> placed in a temporary folder,
/// and runs the associated application for that file extension
/// in a separate process.
/// </summary>
/// <param name="data">The data array.</param>
/// <param name="filename">The filename.</param>
private static void OpenInAnotherApp(byte[] data, string filename)
{
var tempFolder = System.IO.Path.GetTempPath();
filename = System.IO.Path.Combine(tempFolder, filename);
System.IO.File.WriteAllBytes(filename, data);
System.Diagnostics.Process.Start(filename);
}
用法:
var someText = "This is some text.";
var data = Encoding.ASCII.GetBytes(someText);
// open in Notepad
OpenInAnotherApp(data, "somename.txt");
请注意,仅扩展名需要文件名,您可能应该使用随机Guid
或其他东西,并根据已知的 mimetype 附加扩展名。