I am writing some code to add file attachments into an application I am building.
I have add & Remove working but 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#?
Java – How to save byte[] to a file write is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths. get("/path/file"); Files. write(path, bytes);
In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.
Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the write() method of the ImageIo class.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With