How to get execution directory of console application

前端 未结 4 2080
北荒
北荒 2020-12-28 11:36

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

Assembly.GetExecutingAssembly().Location

but this one gives m

相关标签:
4条回答
  • 2020-12-28 11:53

    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");
    
    0 讨论(0)
  • 2020-12-28 11:56

    Use this :

    System.Reflection.Assembly.GetExecutingAssembly().Location
    

    Combine that with

    System.IO.Path.GetDirectoryName if all you want is the directory.
    
    0 讨论(0)
  • 2020-12-28 12:17

    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.

    0 讨论(0)
  • 2020-12-28 12:17

    Safest way:

    string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
    
    0 讨论(0)
提交回复
热议问题