Monday 24 October 2016

"|" Operator inside c# string - how to escape it?




I have following string - which is an argument to execute an exe.



But I am getting error - "Operator "|" can not be applied to operand of type string and string.




Ho do I escape my "|" ? I tried \, didnt work :(



string.Format(
@"-S -E -M -m -e ascii -i {0}.dat -T db1.dbo.table1 -R {1}.reject -t "|" -r \r\n -rt value -rv 1000 -W -fh 0",
saveFilePath + a,
saveFilePath + b);

Answer



In a @"..." literal, to have a " character, you must use two of them. So:




string.Format(
@"-S -E -M -m -e ascii -i {0}.dat -T db1.dbo.table1 -R {1}.reject -t ""|"" -r \r\n -rt value -rv 1000 -W -fh 0",
// note -----------------------------------------------------------------^^-^^
saveFilePath + a,
saveFilePath + b);


However, if you wanted those \r and \n to be a carriage return and a newline, you can't use a @"..." string literal because backslash isn't special in them (that's the whole point of them). So if that's the case:




    string.Format(
"-S -E -M -m -e ascii -i {0}.dat -T db1.dbo.table1 -R {1}.reject -t \"|\" -r \r\n -rt value -rv 1000 -W -fh 0",
// note ^-------------------------------------------------------------------^^-^^
saveFilePath + a,
saveFilePath + b);


Recommended reading: string (C# Reference)







Side note: There's no need for the string concatenation you're doing on the function arguments. Since you're already calling string.Format, you can have it do that:



string.Format(
"-S -E -M -m -e ascii -i {0}{1}.dat -T db1.dbo.table1 -R {2}{3}.reject -t \"|\" -r \r\n -rt value -rv 1000 -W -fh 0",
// note ---------------------^^^^^^--------------------------^^^^^^
saveFilePath,
a, // <==
saveFilePath,
b); // <==


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...