Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

c# - Process.Start in Core 3.0 does not open a folder just by its name

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...