开发过程中经常需要用到获取项目根目录、绝对路径、相对路径等信息,常常记不住,所以在这里记录一下,方便以后查询。
一、WebForm
1、获取IIS启动文件路径
示例:C:\Program Files (x86)\IIS Express\iisexpress.exe
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
2、获取和设置当前目录(该进程从中启动的目录)的完全限定目录
示例:C:\Program Files (x86)\IIS Express
System.Environment.CurrentDirectory;
3、获取应用程序的当前工作目录
示例:C:\Program Files (x86)\IIS Express
System.IO.Directory.GetCurrentDirectory();
4、获取项目的基目录
示例:C:\xxxxxx\Desktop\WeatherService\Web\
System.AppDomain.CurrentDomain.BaseDirectory;
5、获取和设置包括该应用程序的目录的名称
示例:C:\xxxxxx\Desktop\WeatherService\Web\
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
6、Web服务器上的指定虚拟路径相对应的物理文件路径
示例:C:\xxxxxx\Desktop\WeatherService\Web\Image\bb.jpg
Server.MapPath("Image/bb.jpg");
二、WinForm
1、获取宿主应用程序的路径
示例:C:\xxxxxx\Demo\bin\Debug\Demo.vshost.exe
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
2、获取执行程序的根目录
示例:C:\xxxxxx\Demo\bin\Debug
System.Environment.CurrentDirectory;
3、获取执行程序根目录(最后不带\)
示例:C:\xxxxxx\Demo\bin\Debug
System.IO.Directory.GetCurrentDirectory();
4、获取执行程序根目录(最后带\)
示例:C:\xxxxxx\Demo\bin\Debug\
System.AppDomain.CurrentDomain.BaseDirectory;
5、获取执行程序根目录(最后带\)
示例:C:\xxxxxx\Demo\bin\Debug\
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
6、获取启动了应用程序的可执行文件的路径
示例:C:\xxxxxx\Demo\bin\Debug
System.Windows.Forms.Application.StartupPath;
7、获取启动了应用程序的可执行文件的路径及文件名
示例:C:\xxxxxx\Demo\bin\Debug\Demo.EXE
System.Windows.Forms.Application.ExecutablePath;