C#获取当前路径的方法集合

来源:互联网 发布:高性能网络库 编辑:程序博客网 时间:2024/05/16 10:57

//获取当前进程的完整路径,包含文件名(进程名)。
string str = this.GetType().Assembly.Location;
result: X:/xxx/xxx/xxx.exe (.exe文件所在的目录+.exe文件名)

//获取新的 Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名(进程名)。
string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
result: X:/xxx/xxx/xxx.exe (.exe文件所在的目录+.exe文件名)

//获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。
string str = System.Environment.CurrentDirectory;
result: X:/xxx/xxx (.exe文件所在的目录)

//获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。
string str = System.AppDomain.CurrentDomain.BaseDirectory;
result: X:/xxx/xxx/ (.exe文件所在的目录+"/")

//获取和设置包含该应用程序的目录的名称。
string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
result: X:/xxx/xxx/ (.exe文件所在的目录+"/")

//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
string str = System.Windows.Forms.Application.StartupPath;
result: X:/xxx/xxx (.exe文件所在的目录)

//获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
string str = System.Windows.Forms.Application.ExecutablePath;
result: X:/xxx/xxx/xxx.exe (.exe文件所在的目录+.exe文件名)

//获取应用程序的当前工作目录(不可靠)。
string str = System.IO.Directory.GetCurrentDirectory();
result: X:/xxx/xxx (.exe文件所在的目录)

 

 

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

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

举例:

CD E:/app
test/test.exe
那么执行得到的 是 E:/app, 即程序的启动目录, 而不是 程序所在的目录

3. System.IO.Directory.GetCurrentDirectory()
获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,有可能程序放在C:/www里,这个函数有可能返回C:/Documents and Settings/User/,或者C:/Program Files/Adobe/了
(注:此方法取值不固定,随着OpenFileDialog、 SaveFileDialog等对象所确定的目录而改变)

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

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

6. System.Windows.Forms.Application.StartupPath
获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个”/”而已

7. System.Windows.Forms.Application.ExecutablePath
获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。

测试代码

using System;

namespace DetectiveMaker
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
Console.WriteLine(System.Environment.CurrentDirectory);
Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);
Console.WriteLine(System.Windows.Forms.Application.StartupPath);
Console.WriteLine(System.Windows.Forms.Application.ExecutablePath);

//Console.ReadLine();
}
}
}

 

原创粉丝点击