How to get execution directory of console application

*爱你&永不变心* 提交于 2019-11-30 12:23:13

问题


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.


回答1:


Use Environment.CurrentDirectory.

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

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

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




回答2:


Use this :

System.Reflection.Assembly.GetExecutingAssembly().Location

Combine that with

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



回答3:


Safest way:

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



回答4:


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


来源:https://stackoverflow.com/questions/10993721/how-to-get-execution-directory-of-console-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!