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.
StartupPath property returns the path for the executable file that started the application, not the path where the application executable is stored. ExecutablePath property returns the path for the executable file that started the application, including the executable name.
Open Visual Studio, and choose Create a new project in the Start window. In the Create a new project window, select All languages, and then choose C# from the dropdown list. Choose Windows from the All platforms list, and choose Console from the All project types list.
Run the app Press Ctrl + F5 to run the program without debugging. A console window opens with the text "Hello World!" printed on the screen. Press any key to close the console window.
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.
Use this :
System.Reflection.Assembly.GetExecutingAssembly().Location
Combine that with
System.IO.Path.GetDirectoryName if all you want is the directory.
Scott Hanselman has a blog post with the following:
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)}");
}
}
which he uses in .NET Core 3.1, however, I'm running .NET 4.8 and it's working for me.
Safest way:
string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With