Console App Task 08: How to get application running path in C# ?
In C#, you can get the application's running path and append "Output\Log"
using the following methods:
Method 1: Using AppDomain
(Recommended)
using System;
using System.IO;
class Program
{
static void Main()
{
string appPath = AppDomain.CurrentDomain.BaseDirectory;
string logPath = Path.Combine(appPath, "Output", "Log");
Console.WriteLine("Application Path: " + appPath);
Console.WriteLine("Log Path: " + logPath);
// Ensure directory exists
Directory.CreateDirectory(logPath);
}
}
✅ Best for Console & Windows Applications
✅ Gets the path of the executable's directory
Method 2: Using Environment.CurrentDirectory
string appPath = Environment.CurrentDirectory;
string logPath = Path.Combine(appPath, "Output", "Log");
✅ Works but may return different paths depending on execution context.
Method 3: Using Process.GetCurrentProcess()
using System.Diagnostics;
string appPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
string logPath = Path.Combine(appPath, "Output", "Log");
✅ Works even if the app runs as a service
Example Output (if the app runs from C:\MyApp\bin\Debug\
)
Application Path: C:\MyApp\bin\Debug\
Log Path: C:\MyApp\bin\Debug\Output\Log
Final Notes
- Use
Directory.CreateDirectory(logPath);
to ensure the folder exists before writing logs. - Use
Path.Combine()
instead of string concatenation (+
) to ensure cross-platform compatibility.
If you like comment and share. 🚀
0 Comments