I'm working on a console application in C# using .NET 6.0. I have a Journal class that stores entries and a Persistence class to save the journal entries to a file. I'm encountering an error when I try to open the saved text file using Process.Start
. The error message is as follows:
Unhandled exception. System.ComponentModel.Win32Exception (193): An error occurred trying to start process 'c:\temp\journal.txt' with working directory 'C:\Mentorship\Design Patterns\bin\Debug\net6.0'. The specified executable is not a valid application for this OS platform.
relevant part of my code:
var p = new Persistence();
var filename = @"c:\temp\journal.txt";
p.SaveToFile(j, filename);
Process.Start(new ProcessStartInfo(filename));
I'm expecting this code to open the saved text file using the default associated program. However, I'm getting the error mentioned above. How can I resolve this issue and successfully open the text file using Process.Start
in .NET 6.0?
Well, the exception message tells you in plain text:
An error occurred trying to start process 'c:\temp\journal.txt' with working directory 'C:\Mentorship\Design Patterns\bin\Debug\net6.0'. The specified executable is not a valid application for this OS platform.
So, your program tried to execute the journal.txt file like it was a program. This correlates with this code line in your code: Process.Start(filename)
.
Note that this is not a problem with writing the text file as you seem to assume. The problem lies chiefly with trying to execute the written text file like a program.
If your desire is to open the text file in a text editor, then Process.Start(string)
won't help, as it does not work with non-executable files. (It did in the past, but the behavior of Process.Start(string) had been changed with .NET Core 2.1.) To tell the OS to open the text file with the associated application (typically a text editor), you can use the Process.Start(ProcessStartInfo)
method together with explicitly setting ProcessStartInfo.UseShellExecute
to true:
var psi = new ProcessStartInfo(txtFilePath)
{
UseShellExecute = true
};
Process.Start(psi);
In typical Microsoft fashion, the .NET team did not manage to update the official API documentation for Process.Start(string)
reflecting the changed behavior since it was introduced with .NET Core 2.1 in 2018. While there has been a bug report filed regarding the outdated documentation (https://github.com/dotnet/dotnet-api-docs/issues/8727), the documentation issue still persists to this day... :-(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With