作者: littleboy 2023-10-14 16:09:22

C#常用路径操作

当前进程路径

1)获取当前进程的完整路径,包含文件名(进程名)。

1
string str =this.GetType().Assembly.Location;

结果:result: X:xxxxxxxxx.exe (.exe 文件所在的目录+.exe 文件名)

2)获取新的 Process
组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名(进程名)。

1
2
string str =
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

结果:result: X:xxxxxxxxx.exe (.exe 文件所在的目录+.exe 文件名)

3)获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。

1
string?str?=?System.Environment.CurrentDirectory;

结果:result: X:xxxxxx (.exe 文件所在的目录)

4)获取当前 Thread
的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。

1
string?str?=?System.AppDomain.CurrentDomain.BaseDirectory;

结果:result: X:xxxxxx (.exe 文件所在的目录+"")

5)获取和设置包含该应用程序的目录的名称。

1
string?str?=?System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

结果:result: X:xxxxxx (.exe 文件所在的目录+"")

6)获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。

1
string?str?=?System.Windows.Forms.Application.StartupPath;

结果:result: X:xxxxxx (.exe 文件所在的目录)

7)获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。

1
string?str?=?System.Windows.Forms.Application.ExecutablePath;

结果:result: X:xxxxxxxxx.exe (.exe 文件所在的目录+.exe 文件名)

DLL的绝对路径

获取Assembly的运行路径

1
2
3
4
5
6
7
8
9
10
11
12
13
private string GetAssemblyPath()
{
string _CodeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
// 8是file:// 的长度
_CodeBase = _CodeBase.Substring(8, _CodeBase.Length - 8);
string[] arrSection = _CodeBase.Split(new char[] { '/' });
string _FolderPath = "";
for (int i = 0; i < arrSection.Length - 1; i++)
{
_FolderPath += arrSection[i] + "/";
}
return _FolderPath;
}
1
2
3
4
public String GetAssemblyPath()
{
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}

参考:C#获取类库(DLL)的绝对路径