网上找的一些方法:
// 获取程序的基目录。
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:\b
当程序A调用程序B时,程序B中的Environment.CurrentDirectory结果是D:\a,而不是D:\b!!
当遇到这样的情况时,解决方案是:
把所有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文件中。