I am creating a C# console application for some test project, in which I need to get Root folder location (application path) of project, for example, if my project is in "C:\Project\Program.cs
", so i should get "C:\Project\
" drive as root location.
How can I get it using C# console application, in web-application we get it using Server.MapPath("~/")
but I am not sure about console application.
You cannot directly get URL for root folder of your project in Console Application, like Web-application, as console application run from "\bin\debug", so you will have to use this code
// to get the location the assembly is executing from
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
//once you have the path you get the directory with:
var directory = System.IO.Path.GetDirectoryName(path);
to get the location where "Program.cs" file resides or you can say exact root of console project, try this workaround
//returns url of main directory which contains "/bin/Debug"
var url=System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
//correction in path to point it in Root directory
var mainpath = url.Replace("\\bin\\Debug", "");
mainpath = "C:\YourProjectName".
OR
var url = System.AppContext.BaseDirectory; //returns path "C:\..\bin\debug"
You can use 'System.AppContext.BaseDirectory
' in .NET Core Console application or .NET 4.6 to get application path.
OR
System.Reflection.Assembly.GetExecutingAssembly().CodeBase
I will say it is better to use first method 'System.AppContext.BaseDirectory
'. Since 'Assembly.Codebase' is obsolete.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly