Reputation: 135
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?
Upvotes: 4
Views: 5411
Reputation: 106
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.
Upvotes: 1
Reputation: 261
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");
Upvotes: 21