命令行使用string.Format()处理转义字符
本文关键字:处理 转义字符 Format string 命令行 | 更新日期: 2023-09-27 18:03:19
谢谢你看我的帖子。
下面是我喜欢在c#代码中调用的命令行:
C:'>"D:'fiji-win64'Fiji.app'ImageJ-win64.exe" -eval "run('Bio-Formats','open=D:''Output''Untitiled032''ChanA_0001_0001_0001_0001.tif display_ome-xml')"
这是我可以从控制台窗口看到的命令,它运行并提供了我需要的东西。我想从我的c#代码中运行这个命令行,所以有转义字符问题,我不知道如何处理
有两个字符串我想让它们灵活
D: ' fiji-win64 ' Fiji.app ' ImageJ-win64.exe
D: '输出' Untitiled032 ' ChanA_0001_0001_0001_0001.tif
我想知道如何使用string.Format()
来制定这个命令行?
这是我当前的代码,它打开了图像,但display_ome-xml
没有被调用:
string bioformats = "Bio-Formats";
string options = string.Format("open={0} display_ome-xml", fileName.Replace("''", "''''"));
string runCommand = string.Format("run('"'{0}''",'"'{1}''")", bioformats, options);
string fijiCmdText = string.Format("/C '"'"{0}'" -eval {1}", fijiExeFile, runCommand);
在fijiExeFile
起作用的地方,只是runCommand
一直忽略display_ome-xml
。有人有什么建议吗?这真的很令人困惑。非常感谢。
正如@Kristian指出的,@
可以在这里提供帮助。上面的代码中似乎也有一些额外的或放错位置的'"
。这似乎给出了所需的输出字符串:
string fijiExeFile = @"D:'fiji-win64'Fiji.app'ImageJ-win64.exe";
string fileName = @"D:''Output''Untitiled032''ChanA_0001_0001_0001_0001.tif";
string bioformats = "Bio-Formats";
string options = string.Format("open={0} display_ome-xml", fileName);
string runCommand = string.Format("run('{0}','{1}')", bioformats, options);
string fijiCmdText = string.Format("'"{0}'" -eval '"{1}'"", fijiExeFile, runCommand);
最简单的方法是使用逐字字符串文字。只需在字符串前面加一个@,如下所示:
@"c:'abcd'efgh"
这将禁用反斜杠转义字符
如果你需要在你的字符串中包含",你必须像这样转义引号:
@"c:'abcd'efgh.exe ""param1"""
你的例子可以是:
String.Format(@"""{0}"" -eval ""run('Bio-Formats','open={1} display_ome-xml')""", @"D:'fiji-win64'Fiji.app'ImageJ-win64.exe", @"D:'Output'Untitiled032'ChanA_0001_0001_0001_0001.tif")
或
string p1 = "D:''fiji-win64''Fiji.app''ImageJ-win64.exe";
string p2 = "D:''Output''Untitiled032''ChanA_0001_0001_0001_0001.tif";
String.Format(@"""{0}"" -eval ""run('Bio-Formats','open={1} display_ome-xml')""", p1, p2);