转义c#中的命令行参数,用于url、本地路径和网络路径
本文关键字:路径 url 网络 用于 命令行 参数 转义 | 更新日期: 2023-09-27 18:08:25
如何向控制台应用程序提供自动转义的输入字符串?
我的意思是在我的代码中,我可以做public static void main(string[] args)
{
string myURL;
myFolder = @"C:'temp'january'"; //just for testing
myFolder = args[0]; // I want to do this eventually
}
我如何提供值到myFolder,而不必通过命令行手动转义它?
如果可能的话,我想避免像这样调用这个应用程序:
C:'test> myapplication.exe "C:''temp''january''"
编辑:相反,如果可能的话,我更喜欢这样调用应用程序
C:'test> myapplication.exe @"C:'temp'january'"
谢谢。
编辑:这实际上是一个调用Sharepoint Web服务的控制台应用程序。我试着
string SourceFileFullPath, SourceFileName, DestinationFolder, DestinationFullPath;
//This part didn't work. Got Microsoft.SharePoint.SoapServer.SoapServerException
//SourceFileFullPath = args[0]; // C:'temp'xyz.pdf
//SourceFileName = args[1]; // xyz.pdf
//DestinationFolder = args[2]; // "http://myserver/ClientX/Performance" Reports
//This worked.
SourceFileFullPath = @"C:'temp'TestDoc2.txt";
SourceFileName = @"TestDoc2.txt";
DestinationFolder = @"http://myserver/ClientX/Performance Reports";
DestinationFullPath = string.Format("{0}/{1}", DestinationFolder, SourceFileName);
如果字符串不是逐字字符串(以@
开头),则转义'
的要求是c#的一个特性。当你从控制台启动你的应用程序时,你在c#之外,并且控制台不认为'
是一个特殊字符,所以C:'test> myapplication.exe "C:'temp'january"
将工作。
编辑:我原来的帖子上面有"C:'temp'january'"
;然而,Windows命令行似乎也将'
作为转义字符处理——但只有在"
前面时,这样命令才会将C:'temp'january"
传递给应用程序。感谢@zimdanen指出这一点。
请注意,c#中引号之间的任何东西都是字符串的表示;实际的字符串可能不同—例如,''
表示单个'
。如果您使用其他方法将字符串放入程序中,例如命令行参数或从文件中读取,则字符串不需要遵循c#的字符串文字规则。命令行有不同的表示规则,其中'
表示自己。
"前缀" @ "允许使用关键字作为标识符,这在与其他编程语言接口时非常有用。字符@实际上不是标识符的一部分,因此在其他语言中,标识符可能被视为普通标识符,没有前缀。带有@前缀的标识符称为逐字标识符。对于非关键字的标识符,允许使用@前缀,但出于风格考虑,强烈不建议使用。
- 你可以使用c#的一个保留字和@符号
交货:
string @int = "senthil kumar";
string @class ="MCA";
2。在字符串之前,特别是在使用文件路径
时string filepath = @"D:'SENTHIL-DATA'myprofile.txt";
代替
string filepath = "D:''SENTHIL-DATA''myprofile.txt";
对于多行文本
string ThreeIdiots = @"Senthil Kumar,诺顿Stanley)
MessageBox.Show(ThreeIdiots);
string ThreeIdiots = @"Senthil Kumar,'n Norton Stanley,and Pavan Rao!";