本文记录在 dotnet 下,启动进程,传入不存在的文件夹作为进程的工作目录,分别在 .NET Framework 和 .NET Core 的行为

在 dotnet 6 下,可以使用 ProcessStartInfo 辅助创建 Process 进程,如以下代码进行测试,传入不存在的 Z:\Windows 文件夹

Console.WriteLine($"Fx {Environment.CurrentDirectory}");

if (args.Length > 0)
{
    return;
}

var location = Assembly.GetExecutingAssembly().Location;
var fileName = Path.GetFileNameWithoutExtension(location);
var directory = Path.GetDirectoryName(location);

var exe = Path.Combine(directory, fileName + ".exe");
var processStartInfo = new ProcessStartInfo(exe,"fx")
{
    WorkingDirectory = "Z:\\Windows"
};
var process = Process.Start(processStartInfo);

运行将会在 Process.Start 方法上抛出 System.ComponentModel.Win32Exception 说 目录名称无效

如果是在英文环境下,将会提示 The directory name is invalid 从而失败

但如果没有设置 ProcessStartInfo 的 WorkingDirectory 工作路径,那么默认将使用当前进程的 Environment.CurrentDirectory 值作为启动进程的工作路径

在 .NET Core 和 .NET Framework 下,启动时,设置 UseShellExecute 分别为 true 和 false 的值,行为有所不同。在不设置 ProcessStartInfo 的 WorkingDirectory 工作路径,让新的进程默认使用 Environment.CurrentDirectory 工作文件夹。但是此工作路径是一个被插拔的 U 盘的路径,如以下代码

            Environment.CurrentDirectory = @"I:\";

            var exe = Path.Combine(directory, fileName + ".exe"); // 执行到这句代码的时候,拔出 U 盘,让 I:\ 不存在
            var processStartInfo = new ProcessStartInfo(exe, "fx")
            {
                UseShellExecute = true, // 也设置为 false 的值
            };
            var process = Process.Start(processStartInfo);
            process.WaitForExit();

我使用 .NET 6 和 .NET Framework 4.5 进行分别的测试,测试如下:

在 .NET Core 下,设置 UseShellExecute=false 的值,运行结果是:成功,新进程工作路径等于 I:\ 路径

在 .NET Core 下,设置 UseShellExecute=true 的值,运行结果是:成功,新进程工作路径等于 C:\Windows 路径

在 .NET Framework 下,设置 UseShellExecute=false 的值,运行结果是:运行 Process.Start 失败,提示 System.ComponentModel.Win32Exception: '目录名称无效。' 错误

在 .NET Framework 下,设置 UseShellExecute=true 的值,运行结果是:成功,新进程工作路径等于 C:\Windows 路径

更多请看 c# - Win32Exception: The directory name is invalid - Stack Overflow

CreateProcess and ShellExecute differences - Stack Overflow

本文所有代码放在githubgitee 欢迎访问

可以通过如下方式获取本文的源代码,先创建一个空文件夹,接着使用命令行 cd 命令进入此空文件夹,在命令行里面输入以下代码,即可获取到本文的代码

git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin f7696a3e9f33dfcbfdd8ab92afaa77ab668dfeb9

以上使用的是 gitee 的源,如果 gitee 不能访问,请替换为 github 的源

git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git

获取代码之后,进入 HebarlawkuKekebuwagay 文件夹


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/dotnet-%E5%90%AF%E5%8A%A8%E8%BF%9B%E7%A8%8B%E4%BC%A0%E5%85%A5%E4%B8%8D%E5%AD%98%E5%9C%A8%E7%9A%84%E6%96%87%E4%BB%B6%E5%A4%B9%E4%BD%9C%E4%B8%BA%E5%B7%A5%E4%BD%9C%E7%9B%AE%E5%BD%95%E8%A1%8C%E4%B8%BA%E5%8F%98%E6%9B%B4.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

欢迎进入 Eleven 老师组建的 .NET 社区

以上广告全是友情推广,无盈利