The path to the Project (bin) folder at compile time?

Is there any way to find out the project path at compile time?

I want to create a unit test that checks the configuration in the default web.config file (the one that is in the project folder). Mainly to reduce human error.

I cannot rely on build locations at runtime (for a test), so I need to know where the project folder is to access web.config.

I need a โ€œgeneralโ€ solution, since I would like to use the same (basic) test code for several projects, and the physical location in any case for different development machines.

Thanks.

+2
source share
3 answers

If you need the Visual Studio project path, during compilation you can use the Pre-Build Event (see the Project Properties dialog box) to run a command line that will create the source file used in your project.

The source file will contain some code, say, a variable definition. Your test code uses this variable. The value of the variable will be obtained from VS; when he runs the Pre-Build Event command, it replaces the project properties for specific macros. The macro you want is probably ProjectDir.

So, at the end, you have something like this for the Pre-Build Event command:

echo 'const char * PROJECT_PATH = "$(ProjectDir)";' > source.cpp 

Not sure which language you are using, so configure accordingly.

+2
source

Based on rkb answer,

It seems to you that you have a C # project, use this post-build step.

 echo namespace ProjectPath { static public class ProjectPath { public static readonly string Path = @"$(ProjectDir)";} } > $(ProjectDir)path.cs 

Then include path.cs as an existing element in the test project. Then you can access it through:

 string path = ProjectPath.ProjectPath.Path; 
+7
source

To improve the solution a bit, instead of using the Post Build Event command line, you can run this command as an MSbuild Exec task in the target BeforeBuild program of the project.

0
source

Source: https://habr.com/ru/post/1303820/


All Articles