C# 如何获取控制台应用程序的执行目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10993721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:03:27  来源:igfitidea点击:

How to get execution directory of console application

c#.netfilepath

提问by eugeneK

I tried to get the directory of the console application using the below code,

我尝试使用以下代码获取控制台应用程序的目录,

Assembly.GetExecutingAssembly().Location

but this one gives me where the assemble resides. This may be different from where I executed the application.

但是这个给了我集合所在的位置。这可能与我执行应用程序的位置不同。

My console application parses logs with no parameters. It must go to the logs/folder inside of the executable's folder or if I give it a path to logs/it parses it.

我的控制台应用程序解析没有参数的日志。它必须转到logs/可执行文件文件夹内的文件夹,或者如果我给它一个路径,logs/它就会解析它。

采纳答案by Stefan

Use Environment.CurrentDirectory.

使用Environment.CurrentDirectory.

Gets or sets the fully qualified path of the current working directory.
(MSDN Environment.CurrentDirectory Property)

获取或设置当前工作目录的完全限定路径。
(MSDN Environment.CurrentDirectory 属性

string logsDirectory = Path.Combine(Environment.CurrentDirectory, "logs");

If your application is running in c:\Foo\BarlogsDirectorywill point to c:\Foo\Bar\logs.

如果您的应用程序在c:\Foo\Bar 中运行,logsDirectory则将指向 c:\Foo\Bar\logs

回答by dtsg

Safest way:

最安全的方法:

string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

回答by Sunny

Use this :

用这个 :

System.Reflection.Assembly.GetExecutingAssembly().Location

Combine that with

结合它

System.IO.Path.GetDirectoryName if all you want is the directory.

回答by Donovan Phoenix

Here is a simple logging method

这是一个简单的日志记录方法

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);
    }
}

Usage:

用法:

logWrite("Log.txt", "Test");