Home > Back-end >  Exception when using System.Diagnostics.Process.Start to open an EML file
Exception when using System.Diagnostics.Process.Start to open an EML file

Time:12-16

If you save an email to a file on disk with an EML extension, you can open it in Outlook on Windows just by double-clicking the file. I'm hoping to do something similar as my application can encounter EML files that it needs to open.

I have some crude test code that has:

using System;
using System.Diagnostics;
using System.IO;

and then:

System.Diagnostics.Process.Start(@"C:\temp\test.eml");

When I run the code I get the following exception:

System.ComponentModel.Win32Exception: 'An error occurred trying to start process 'C:\temp\test.eml' with working directory 'C:\Users\me\source\repos\TestProj\TestProj\bin\Release\net6.0-windows'. The specified executable is not a valid application for this OS platform.'

I have tried placing a simple text file in the same folder and named it 'test.txt' and checked that it opens in Notepad when I double-click it, but if I try to open it with:

System.Diagnostics.Process.Start(@"C:\temp\test.txt");

I get the same error. Where am I going wrong?

CodePudding user response:

There was a breaking change in .NET Core compared to .NET Framework:

Change in default value of UseShellExecute
ProcessStartInfo.UseShellExecute has a default value of false on .NET Core. On .NET Framework, its default value is true.

Change description
Process.Start lets you launch an application directly, for example, with code such as Process.Start("mspaint.exe") that launches Paint. It also lets you indirectly launch an associated application if ProcessStartInfo.UseShellExecute is set to true. On .NET Framework, the default value for ProcessStartInfo.UseShellExecute is true, meaning that code such as Process.Start("mytextfile.txt") would launch Notepad, if you've associated .txt files with that editor. To prevent indirectly launching an app on .NET Framework, you must explicitly set ProcessStartInfo.UseShellExecute to false. On .NET Core, the default value for ProcessStartInfo.UseShellExecute is false. This means that, by default, associated applications are not launched when you call Process.Start.

Use Process.Start overload accepting ProcessStartInfo and set UseShellExecute to true:

var processStartInfo = new ProcessStartInfo
{
    FileName = @"C:\temp\test.eml",
    UseShellExecute = true
};
Process.Start(processStartInfo);

Otherwise provide path to executable and pass path to file as a parameter:

var pathToOutlook = @"C:\Program Files\Microsoft Office\root\Office16\OUTLOOK.EXE";
Process.Start(pathToOutlook,  @"D:\Downloads\sample.eml");
  • Related