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

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

// 获取程序的基目录。 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。code

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

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

当遇到这样的状况时,我本身的解决方案是:进程

把全部System.Environment.CurrentDirectory改为System.AppDomain.CurrentDomain.BaseDirectory。io

 

网上也有不少人说针对winform能够改为Application.StartupPath。table

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

1. AppDomain.CurrentDomain.BaseDirectory 返回结果为: D:\xxx\ Application.StartupPath 返回结果为: D:\xxx 2. Application.StartupPath 只能用于WinForm窗体中,而AppDomain.CurrentDomain.BaseDirectory既能够用于WinForm窗体中,也能够用于类库DLL文件中。
相关文章
相关标签/搜索