Вопрос

I have a table in my database that stores all kind of files.

File names are shown in a ListView and when an user clics on one of them then it's opened by the registered application based on file extension.

This is the code:

if (listViewArchivos.HasItems)
{
    dynamic result = listViewArchivos.SelectedItem;
    var nombre = Path.GetTempPath() + admin.buscarNombreArchivo((int)result.Id);
    var bytes = admin.buscarArchivo((int)result.Id);

    try
    {
        using (var writer = new BinaryWriter(File.Open(nombre, FileMode.Create)))
        {
            writer.Write(bytes);
        }

        var p = Process.Start(nombre);

        p.WaitForExit();
    }
    catch (Exception exc)
    {
        InterfazUtil.error(exc.Message); // This shows a MessageBox
    }
    finally
    {
        File.Delete(nombre);
    }
}

It's working fine for docx, pdf, txt, etc. But when I try to open an image the file is successfully opened by Window Photo Viewer (Windows 7) but a NullReferenceException is thrown.

If I close WPV first and then the MessageBox the file is deleted from temp folder.

If I close the MessageBox first then the image disappears from WPV and after I close WPV the file is not deleted from temp folder.

Now, if I remove the catch block then the file is successfully opened by WPV and after closing it the file is not deleted from temp folder. Obviously the application crashes because the exception isn't managed.

Looks like the problem is WPV.

Any idea of what is wrong?

TIA

EDIT:

The exception is thrown at

p.WaitForExit();
Это было полезно?

Решение 2

According to this MSDN: http://msdn.microsoft.com/en-us/library/53ezey2s.aspx

...you will not get back a Process object when the process is already running.

I found this on a forum relating to the nature of WindowsPhotoViewer:

Actually, the Windows Photo Viewer is part of Windows Explorer, and generally runs in the Explorer.exe process. In fact, what you're calling the Photo Viewer is really just the "preview" verb for images. It isn't a standalone application, and opening it without an image or images doesn't really make any sense.

Thus, you are not getting back a Process object because it is already running by virtue of the fact that explorer.exe is already running.

In the end, I think it means that if your images open in WindowsPhotoViewer, you will not be able to make WaitForExit() work because the owner process will never exit.

Другие советы

When you close the MessageBox first the temp file is not deleted because WPV uses it and doesn't allow it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top