在.NET应用程序开发中,获取当前路径是非常基础且常用的操作,不同的路径获取方式对应不同的业务场景,开发者需要根据实际需求选择合适的方法。常见的路径类型包括当前工作目录、程序集所在目录、当前执行文件路径等,下面将逐一介绍对应的获取方法。

获取当前工作目录
当前工作目录是指应用程序启动时所在的目录,或者说是进程当前的工作目录,可以通过Environment.CurrentDirectory属性或者Directory.GetCurrentDirectory方法获取,两者的返回结果一致。
using System;
using System.IO;
class Program
{
static void Main()
{
// 方法1:使用Environment类获取当前工作目录
string workDir1 = Environment.CurrentDirectory;
Console.WriteLine("Environment.CurrentDirectory获取的路径:" + workDir1);
// 方法2:使用Directory类获取当前工作目录
string workDir2 = Directory.GetCurrentDirectory();
Console.WriteLine("Directory.GetCurrentDirectory获取的路径:" + workDir2);
}
}
获取程序集所在目录
程序集所在目录是指当前执行的程序集(比如exe或者dll)所在的文件夹路径,适合需要读取同目录下配置文件、资源文件的场景,不会因为工作目录变化而改变。
获取入口程序集所在目录
入口程序集就是应用程序启动的主程序集,通过Assembly.GetEntryAssembly方法获取,再拿到其位置后提取目录。
using System;
using System.IO;
using System.Reflection;
class Program
{
static void Main()
{
// 获取入口程序集
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
// 获取程序集的完整路径
string assemblyPath = entryAssembly.Location;
// 提取目录部分
string assemblyDir = Path.GetDirectoryName(assemblyPath);
Console.WriteLine("入口程序集所在目录:" + assemblyDir);
}
}
}
获取当前执行代码所在程序集目录
如果代码写在类库项目中,需要获取当前类库所在的目录,可以使用Assembly.GetExecutingAssembly方法。
using System;
using System.IO;
using System.Reflection;
class Program
{
static void Main()
{
// 获取当前执行代码所在的程序集
Assembly executingAssembly = Assembly.GetExecutingAssembly();
string executingPath = executingAssembly.Location;
string executingDir = Path.GetDirectoryName(executingPath);
Console.WriteLine("当前执行程序集所在目录:" + executingDir);
}
}
获取当前执行文件的完整路径
如果需要直接获取当前运行的exe或者dll的完整路径,不需要提取目录,也可以直接使用上述程序集的Location属性。
using System;
using System.Reflection;
class Program
{
static void Main()
{
// 获取入口程序集的完整路径
string exePath = Assembly.GetEntryAssembly()?.Location;
Console.WriteLine("当前执行文件完整路径:" + exePath);
}
}
不同方法的适用场景对比
为了更清晰地选择方法,下面整理了不同获取方式的适用场景和特点:
| 获取方式 | 返回路径类型 | 适用场景 |
|---|---|---|
| Environment.CurrentDirectory | 当前工作目录 | 需要操作进程当前工作目录下的文件时使用 |
| Directory.GetCurrentDirectory | 当前工作目录 | 和Environment.CurrentDirectory一致,更偏向IO操作场景 |
| Assembly.GetEntryAssembly().Location | 入口程序集完整路径 | 需要读取主程序同目录下的资源、配置文件时使用 |
| Assembly.GetExecutingAssembly().Location | 当前代码所在程序集完整路径 | 类库项目中需要获取自身所在目录时使用 |
注意事项
- 当前工作目录可能会被其他代码修改,比如调用
Directory.SetCurrentDirectory方法,因此如果需要固定路径,优先选择程序集所在目录的获取方式。 - 在ASP.NET Core等Web应用中,获取路径的方式和桌面应用有差异,Web应用通常使用
IWebHostEnvironment的ContentRootPath或者WebRootPath属性,不要直接使用上述桌面应用的方法。 - 使用
Path.GetDirectoryName方法提取目录时,不需要手动处理路径分隔符,该方法会自动适配不同操作系统的路径规则。
.NET当前路径获取路径Path类Environment类修改时间:2026-07-08 23:15:28