Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get C# (.net core) project directory path in Visual Studio 2017 RC3?

I have a C# (.Net Core) solution in visual studio 2017 RC3 that contains many projects (4 if you are curious) and that I recently migrated from the old project.json/visual studio 2015 format by using VS 2017 RC3.

One of the projects is a test project, in which I need to access some files contained under it.

It seems that Directory.GetCurrentDirectory() cannot be relied upon to get the projects path in the test code, since tests , in VS 2017, are ran from the IDE's installation location C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE.

Currently I am working around this by hard-coding the test project's base path. As this is not ideal, is there an alternative to programatically get the base path of a project in VS 2017 RC3?

like image 376
Chedy2149 Avatar asked Jan 31 '17 21:01

Chedy2149


People also ask

Is C+ Same as C?

C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language. C is (mostly) a subset of C++.

Is C+ difficult to learn?

C++ is hard to learn because of its multi-paradigm nature and more advanced syntax. While it's known to be especially difficult for beginners to learn, it's also difficult for programmers with no experience with low-level languages.


2 Answers

You should be able to get what you want with AppContext.BaseDirectory. This will return where the tests are running from %projectfolder%\bin\debug\netcoreapp1.1. You could do something like this to get the project folder.

AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.IndexOf("bin"));

You could throw this into a helper or extension method.

like image 76
Matthew Avatar answered Oct 05 '22 05:10

Matthew


Following on Matthew's answer, I ended up with this code (VSCode/.net-core/C#/MacOSX) to get the actual solution root versus the project root:

var appRoot = AppContext.BaseDirectory.Substring(0,AppContext.BaseDirectory.LastIndexOf("/bin"));
appRoot = appRoot.Substring(0,appRoot.LastIndexOf("/")+1);

The +1 bit allows you to include the trailing forward slash.

like image 31
Shane K Avatar answered Oct 05 '22 04:10

Shane K