3

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.
    }
}

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

6 Comments

Putting it in the resources is a nice idea. Didn't think of that one before.
I hope that answer is good enough for you and it worked. I just thought about another workaround: you could write var dir = "__PROJDIR__" and in the prebuild step you could search & replace __PROJDIR__ with $(ProjectDir).
But it would always come to a pre-build step. That's something I would like to avoid.
Why would you like to avoid the prebuild step?
Because I have over 100 csproj files that will need the same code. There still isn't something like a pre-build step solution wide. Except for a .bat file of course. But then I would still have to add the bat file to all 100 projects.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.