Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open byte-array as file windows forms

In a windows forms application I have a file stored as a byte[].

When the user clicks the button I want to open the file without saving it local. Is this possible? If it is then how?

Or do I have to save the byte-array as a local file an run this file then?

Thanks, Karl

like image 885
abc Avatar asked Mar 23 '23 11:03

abc


1 Answers

If you want to open in in an application (just like Windows would if you double-clicked a file with an appropriate extension), you will have to write its contents to a file:

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

Usage:

var someText = "This is some text.";
var data = Encoding.ASCII.GetBytes(someText);

// open in Notepad
OpenInAnotherApp(data, "somename.txt");

Note that the file name is needed only for the extension, you should probably use a random Guid or something and append the extension based on a known mimetype.

like image 58
Groo Avatar answered Mar 31 '23 16:03

Groo