获取当前exe文件所在目录 C#
时间: 2023-07-01 11:09:32 浏览: 260
可以使用以下代码获取当前exe文件所在目录:
```csharp
string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeDir = System.IO.Path.GetDirectoryName(exePath);
```
第一行获取当前正在执行的程序集的路径,第二行使用 `Path.GetDirectoryName` 方法获取该路径的父目录。注意,这里得到的是绝对路径,而不是相对于当前工作目录的相对路径。
相关问题
C#获取当前调用本dll的exe文件的目录
可以使用`System.Reflection.Assembly.GetExecutingAssembly().Location`获取当前dll所在的路径,然后通过`System.IO.Path.GetDirectoryName`方法获取该路径所在的目录,即为调用该dll的exe文件的目录。下面是示例代码:
```csharp
using System;
using System.IO;
using System.Reflection;
public static class DllHelper
{
public static string GetExecutingExeDirectory()
{
string dllPath = Assembly.GetExecutingAssembly().Location;
string exePath = Path.GetDirectoryName(dllPath);
return exePath;
}
}
```
在调用该方法时,即可获取当前调用该dll的exe文件的目录。
如何在C#中获取当前运行程序所在的目录并访问其子目录CONFIG中的文件?
在C#中,你可以使用`Directory`和`File`类来获取当前运行程序的目录以及访问其子目录。以下是一个示例:
```csharp
using System.IO; // 引入需要的System.IO命名空间
// 获取应用程序的安装目录
string appDirectory = Application.StartupPath;
// 或者,如果你不确定是否在安装目录,可以这样获取:
// string appDirectory = Directory.GetCurrentDirectory();
// 定义配置文件路径,假设它位于应用目录的"CONFIG"子目录下
string configFilePath = Path.Combine(appDirectory, "CONFIG", "yourConfigFile.txt");
try {
// 尝试打开文件
using (StreamReader reader = new StreamReader(configFilePath)) {
string content = reader.ReadToEnd();
Console.WriteLine($"Content of the configuration file: {content}");
}
}
catch (FileNotFoundException) {
Console.WriteLine("The configuration file does not exist.");
}
阅读全文
相关推荐













