How can I get application root folder location in C# Console application?


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.


Asked by:- bhanu
1
: 12479 At:- 9/18/2020 7:35:58 AM
C# console application path root folder console application







2 Answers
profileImage Answered by:- vikas_jk

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"
2
At:- 9/18/2020 2:13:35 PM Updated at:- 11/16/2022 9:42:27 AM
Excellent, Now I understand, I was getting "bin\debug" folder location, I had to replace it to get exact root location, thanks. 0
By : bhanu - at :- 9/27/2020 3:22:57 PM


profileImage Answered by:- jaiprakash

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.

0
At:- 11/16/2022 3:57:09 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use