Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file with Windows default Application

Tags:

c#

pdf

.net-5

I am using C# .NET 5.0 to list PDF files on a folder and when double clicked on a item it opens the selected PDF with the windows default PDF viewer.
I've searched how to do this, but the solution code throws an exception.

System.Diagnostics.Process.Start(@"C:\path\to\pdf\file.pdf");

Error:

System.ComponentModel.Win32Exception: 'The specified executable is not a valid application for this OS platform.'

Can someone help me?

like image 378
Felipe K. Bernardino Avatar asked Oct 24 '25 11:10

Felipe K. Bernardino


2 Answers

Had this same issue when trying to open a excel spreadsheet.

.Net Framework used to have the UseShellExecute default to true, .Net 5.0 will default it to false.

In short, UseShellExecute as false it will use the CreateProcess instead of the ShellExecute and will have the same effect as running a command on your terminal.

By using the code below you should be able to run it as long as you have a program assotiated with that extension.

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = @"C:\path\to\pdf\file.pdf";
psi.UseShellExecute = true;
Process.Start(psi);

If you don't want to do this way you can also specify what program binary to use and what file to open, for example you could use edge to open the PDF file like so:

Process.Start(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", @"C:\path\to\pdf\file.pdf");
like image 164
Philippe Canavarro Avatar answered Oct 26 '25 04:10

Philippe Canavarro


You can do something like this:

public static bool OpenWithDefaultProgram(string path)
{
    if (!File.Exists(path))
        return false;
    using Process process = Process.Start(new ProcessStartInfo()
    {
        FileName = "explorer",
        Arguments = $"{path}"
    });
    process.WaitForExit();
    return process.ExitCode == 1;
}

In order to ensure that nothing unexpected happens if the file does not exist, you should check for it.

like image 22
Philipp Schumacher Avatar answered Oct 26 '25 03:10

Philipp Schumacher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!