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
0
: 409 At:- 9/18/2020 7:35:58 AM
C# console application path root folder console application






1 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".

1
At:- 9/18/2020 2:13:35 PM
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






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

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly