如何获取控制台应用程序的执行目录
本文关键字:应用程序 执行 控制台 何获取 获取 | 更新日期: 2023-09-27 18:37:04
我试图使用以下代码获取控制台应用程序的目录,
Assembly.GetExecutingAssembly().Location
但是这个给了我组装所在的位置。这可能与我执行应用程序的位置不同。
我的控制台应用程序分析不带参数的日志。它必须转到可执行文件文件夹内的logs/
文件夹,或者如果我给它一个路径来logs/
它会解析它。
使用 Environment.CurrentDirectory
.
获取或设置当前工作目录的完全限定路径。
(MSDN Environment.CurrentDirectory 属性)
string logsDirectory = Path.Combine(Environment.CurrentDirectory, "logs");
如果您的应用程序在 c:''Foo''Bar 中运行,logsDirectory
将指向 c:''Foo''Bar''logs。
使用这个:
System.Reflection.Assembly.GetExecutingAssembly().Location
将其与
System.IO.Path.GetDirectoryName if all you want is the directory.
Scott Hanselman有一篇博客文章,内容如下:
using System;
using System.Diagnostics;
using System.IO;
namespace testdir
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Launched from {Environment.CurrentDirectory}");
Console.WriteLine($"Physical location {AppDomain.CurrentDomain.BaseDirectory}");
Console.WriteLine($"AppContext.BaseDir {AppContext.BaseDirectory}");
Console.WriteLine($"Runtime Call {Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)}");
}
}
他在 .NET Core 3.1 中使用,但是,我正在运行 .NET 4.8,它对我有用。
最安全的方法:
string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
这是一个简单的日志记录方法
using System.IO;
private static void logWrite(string filename, string text)
{
string filepath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "''" + filename;
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(text);
Console.WriteLine(text);
}
}
用法:
logWrite("Log.txt", "Test");