C#: 获取当前路径不要用Environment.CurrentDirectory

网上大把文章写到C#获取当前路径的方法如下:

// 获取程序的基目录。
System.AppDomain.CurrentDomain.BaseDirectory

// 获取模块的完整路径。
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

// 获取和设置当前目录(该进程从中启动的目录)的完全限定目录。
System.Environment.CurrentDirectory

// 获取应用程序的当前工作目录。
System.IO.Directory.GetCurrentDirectory()

// 获取和设置包括该应用程序的目录的名称。
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase

// 获取启动了应用程序的可执行文件的路径。
System.Windows.Forms.Application.StartupPath

// 获取启动了应用程序的可执行文件的路径及文件名
System.Windows.Forms.Application.ExecutablePath

我以前写的代码中获取当前路径基本上都是使用的System.Environment.CurrentDirectory。

但是最近在用另外一个程序A去调用以前的程序B的时候就出现问题了,程序A的作用只是单纯调取程序B的exe文件,在B执行过程中总是真到当前路径这块就出现了问题,实际找到的路径是程序A的路径。

程序A目录:D:a
程序B目录:D:
当程序A调用程序B时,程序B中的Environment.CurrentDirectory结果是D:a,而不是D:!!

当遇到这样的情况时,我自己的解决方案是:

把所有System.Environment.CurrentDirectory改成System.AppDomain.CurrentDomain.BaseDirectory。

网上也有很多人说针对winform可以改成Application.StartupPath。

C# WinForm中AppDomain.CurrentDomain.BaseDirectory与Application.StartupPath的区别示例如下:

1. AppDomain.CurrentDomain.BaseDirectory 返回结果为: D:xxx
Application.StartupPath 返回结果为: D:xxx
2. Application.StartupPath 只能用于WinForm窗体中,而AppDomain.CurrentDomain.BaseDirectory既可以用于WinForm窗体中,也可以用于类库DLL文件中。
原文地址:https://www.cnblogs.com/danvy/p/10228840.html