Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use MSBuild macro like $(ProjectDir) in C# code

Tags:

c#

msbuild

Can I use MSBuild variables so that they are resolved in my code? I am thinking of a piece of code that requires the $(ProjectDir), because it will never be moved (it is a unit test project).

An example:

public class MyTestDataPath
{
    public void GetTestData()
    {
        return SOME_COMPILE_TIME_PROJECT_DIR_MACRO + "\\test-data"; // Should resolve via $(ProjectDir) during compile time.
    }
}
like image 643
Marnix Avatar asked Feb 20 '26 00:02

Marnix


1 Answers

Yes, there is. But not directly in your code. You could define a prebuild action in your project properties:

echo $(ProjectDir) > "$(ProjectDir)\Resources\ProjDir.txt"

Then you can add the file projdir.txt as a resource in your project properties and reference the content in your code with:

var dir = Resources.ProjDir

But I would simply copy the test data in your postbuild action into the output directory and use reflection to get it at runtime (binaries and test data are now portable to other developers).

like image 152
anscheinbar Avatar answered Feb 21 '26 15:02

anscheinbar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!