imekon
imekon

Reputation: 1543

Environment variables in Visual Studio solution files

I have a Visual Studio solution which has the following entry for one specific project:

Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XXXData",
"%XXX_LIBS_DIR%\XXXData\XXXData\XXXData.csproj", "{AA390915-1F94-459F-A3D8-B2027A90A6AF}"
EndProject

This works fine in Visual Studio but falls over building with MSBUILD, as you get:

E:\path\project.sln.metaproj : error MSB2302: The project file
"E:\path\%XXX_LIBS_DIR%\XXXData\XXXData.csproj" was not found

It looks like %XXX_LIBS_DIR% is not being translated by MSBUILD so it can't find the project file.

I did try replacing %XXX_LIBS_DIR% with $(XXX_LIBS_DIR) however this doesn't work in Visual Studio.

One thought that I considered was to pre process the solution and replace %XXX_LIBS_DIR% with an absolute or relative path and see if that works, I was wondering if there was a better solution than that?

Upvotes: 1

Views: 3327

Answers (2)

Leo Liu
Leo Liu

Reputation: 76890

Update

Usage of environment variables in .sln files through msbuild.exe is fixed on VS2019 MSBuild v16.0 based on the referenced issue.


Environment variables in Visual Studio solution files

This is a known issue about MSBuild, see:

https://github.com/Microsoft/msbuild/issues/120

And

https://developercommunity.visualstudio.com/content/problem/248631/msbuild-doesnt-parse-environment-variables-in-sln.html

"Currently we are using environment variables to specify where to find projects within our VS solution files. Visual Studio seems to handle this fine but when trying to build the solution via MSBuild, we get an error due to it not parsing the environment variable at all."

MS team marked "Won't Fix" in 2011.

So, for this issue, I am afraid there is no better solution to solve this issue than give it with an absolute or relative path.

Hope this helps.

Upvotes: 1

cowlinator
cowlinator

Reputation: 8813

As @LeoLiu-MSFT mentioned, environment variables in solution files are unfortunately not supported by msbuild.

You will need to replace the variables with the actual values before building.

Example:

# Python 2.7 or 3.7+
# usage: python fix_sln.py path/to/file.sln
import codecs
import os
import re
import shutil
import sys

if __name__ == "__main__":
    with codecs.open(sys.argv[1], encoding='utf-8-sig') as orig:
        with codecs.open(sys.argv[1] + '.modified', 'w', encoding='utf-8-sig') as new:
            for line in orig:
                line = line.rstrip('\r\n')
                found = re.search(r"""%.+%""", line)
                line = line.replace(str(found.group()), os.environ.get(str(found.group()).replace("""%""", ""))) if found else line
                new.write(line + '\r\n')
    shutil.move(sys.argv[1] + '.modified', sys.argv[1])

Upvotes: 0

Related Questions