1

I have a program where the users can save an attachment for a contract. The attachment is saved in the database a a varbinary. The users can then view the attachment.

I am saving the file to a temp location while they view it and then deleting the file after the process is closed. This is working fine for word and excel documents but not for jpeg files.

File.WriteAllBytes(@"C:\Temp\" + SelectedAttachment.FileName + SelectedAttachment.FileType, SelectedAttachment.FileBlob);

                //open the file for viewing
                var attachmentProcess = System.Diagnostics.Process.Start(@"C:\Temp\" + SelectedAttachment.FileName + SelectedAttachment.FileType);
                attachmentProcess.WaitForExit();


                //Delete temp file after user closes the file
                File.Delete(@"C:\Temp\" + SelectedAttachment.FileName + SelectedAttachment.FileType);

The attachmentProcess.WaitForExit(); throws an 'System.NullReferenceException' but was not handled in user code error when the .jpeg opens. The file will open regardless of the error but does not delete upon closing the file.

I have tried using

using (Image image = Image.FromStream(new MemoryStream(SelectedAttachment.FileBlob)))
                {
                    image.Save("output.jpg", ImageFormat.Jpeg);  
                }

but i get an error stating that " 'Image': type used in a using statement must be implicitly convertible to 'System.IDisposable'

Is there a way to get the .jpeg file process to behave like the word or excel files or should I use the MemoryStream route and if so what am i doing wrong there?

Helmbo
  • 33
  • 8
  • Google "process.start returns null". Google "system.drawing.image". – Hans Passant Jul 20 '16 at 17:01
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Thomas Weller Jul 20 '16 at 17:02

1 Answers1

1

You are using a static version of the Process.Start method and passing in a file name (which since it is an image, I'm guessing it is being treated like a url and opening in the web browser via file:///your-file-path/file-name). This actually returns null rather than a process, hence your error. You should instead pass in the name of a program (e.g. your web browser) and the filename as a parameter (using this version of the method).

Otherwise, consider creating a process object (via the new keyword, likely wrapped in a using statement) and calling the start method on that instance with your given StartInfo properties. This will ensure you have an actual process object in which to wait for exit.

Jason Down
  • 21,731
  • 12
  • 83
  • 117