如何在Visual Studio模板参数中转义反斜杠
解决Visual Studio项目模板中launchSettings.json里$solutiondirectory$的斜杠转义问题
在创建AutoCAD C#项目模板时,需要在launchSettings.json的commandLineArgs中使用$solutiondirectory$参数指定完整路径,以此避免依赖LEGACYCODESEARCH系统变量。但该参数返回的是带单反斜杠的路径字符串(例如C:\Users\username\source\repos\Acad2025Plugin),而JSON语法要求路径中的反斜杠必须以双反斜杠(转义格式)表示,直接使用会导致路径格式错误。
错误示例
以下是未正确处理斜杠转义的launchSettings.json代码:
{ "profiles": { "$projectname$": { "commandName": "Executable", "executablePath": "C:\\Program Files\\Autodesk\\AutoCAD 2025\\acad.exe", "commandLineArgs": "/nologo /b \"$solutiondirectory$\\$projectname$\\start.scr\"" } } }
解决方案
可以通过两种方式实现斜杠的自动转义:
方法1:直接在参数中使用字符串替换
在launchSettings.json的模板文件里,将$solutiondirectory$替换为带字符串替换逻辑的表达式,自动把单反斜杠转为双反斜杠:
{ "profiles": { "$projectname$": { "commandName": "Executable", "executablePath": "C:\\Program Files\\Autodesk\\AutoCAD 2025\\acad.exe", "commandLineArgs": "/nologo /b \"$solutiondirectory.Replace(@\"\\\", @\"\\\\\")$\\$projectname$\\start.scr\"" } } }
方法2:在模板中定义自定义转义参数
- 打开项目模板的
.vstemplate文件,在<TemplateContent>节点下添加自定义参数:
<CustomParameters> <CustomParameter Name="$SolutionDirectoryEscaped$" Value="$solutiondirectory$.Replace("\", "\\\\")" /> </CustomParameters>
- 在launchSettings.json中调用这个已转义的自定义参数:
{ "profiles": { "$projectname$": { "commandName": "Executable", "executablePath": "C:\\Program Files\\Autodesk\\AutoCAD 2025\\acad.exe", "commandLineArgs": "/nologo /b \"$SolutionDirectoryEscaped$\\$projectname$\\start.scr\"" } } }
两种方法都能确保生成的launchSettings.json中,路径反斜杠被正确转换为JSON要求的双反斜杠格式。
内容的提问来源于stack exchange,提问作者gileCAD
相关产品推荐
相关产品推荐

