Process.Start in Core 3.0 does not open a folder just by its name
Asked Answered
M

1

12

I have just migrated a desktop app from Framework to Core 3.0.

Process.Start(path_to_folder); workes fine in Framework but throws Win32Exception: Access denied in the Core. Process.Start("explorer.exe", path_to_folder); works fine on both.

Is this a bug or limitation in the Core?

Minnieminnnie answered 13/11, 2019 at 22:38 Comment(1)
Sounds more like the old behavior is an unintended side-effect of how things were done in .NET Framework, as Process.Start(string) was always meant to take a file name, not a folder path.Cannonball
C
17

I suspect the ProcessStartInfo.UseShellExecute property is what would allow this to work on .NET Framework. From the documentation...

The default is true on .NET Framework apps and false on .NET Core apps.

...and the Process.Start() overloads that just take string parameters will likely just leave that property at the default. To work around this, create your own ProcessStartInfo with the UseShellExecute property set to true and pass that to an overload of Process.Start() instead...

ProcessStartInfo startInfo = new ProcessStartInfo(path_to_folder) {
    UseShellExecute = true
};

Process.Start(startInfo);

For completeness, when I try running this...

Process.Start(Environment.SystemDirectory);

...in .NET Core 3.0 I get this exception...

Unhandled exception. System.ComponentModel.Win32Exception (5): Access is denied.

The missing link between Process.Start() and Process.StartWithCreateProcess(ProcessStartInfo startInfo) is Process.StartCore(ProcessStartInfo startInfo), which branches based on the value of UseShellExecute and I imagine gets inlined. The exception appears to be thrown after a call to CreateProcess(), presumably because a directory path is specified as the file to executable.

Note that if you pass a path to a non-executable file to that same Process.Start(String fileName) overload the exception message becomes "The specified executable is not a valid application for this OS platform."

The reason why calling Process.Start(String fileName, String arguments) works despite following largely the same code path is because the ProcessStartInfo instance it creates under the covers has a FileName property that does refer to a file (explorer.exe) that can be directly executed even if UseShellExecute is false.

Crump answered 13/11, 2019 at 23:26 Comment(1)
Yes, it works with the property defined. It's worth mentioning that the path should be defined in the FileName property in this case.Minnieminnnie

© 2022 - 2024 — McMap. All rights reserved.