Adding a string to the verbatim string literal

落爺英雄遲暮 提交于 2019-11-30 22:57:33

Do it like this (preferred):

string.Format(@"""C:\Mavro\MavBridge\Server\MavBridgeService.exe"" /service /data ""..\{0}""", defaultPath);

Or like this:

@"""C:\Mavro\MavBridge\Server\MavBridgeService.exe"" /service /data ""..\" + defaultPath + "\"";

The first one uses string.Format, which basically replaces the {0} in the first parameter with the value in the second parameter and returns the result.

The second one uses classical string concatenation and what I did there was to remove the double quotes after the last backslash (""..\ instead of ""..\""), because you didn't want the quotes after the backslash. You wanted the quotes after defaultPath. And that's what this code does: It appends defaultPath (" + defaultPath) and appends the closing quote afterwards (+ "\"").

Use string.Format to insert the variable between the quotes:

string path = "Data.Apple";
string verbatim = string.Format(@"""C:\Mavro\MavBridge\Server\MavBridgeService.exe"" /service /data ""{0}""", path);
MessageBox.Show(verbatim);

It makes it easier to read and to implement, you can replace other portions of the path with variable sections in a similar manner.

If you try to just append the "defaultPath" variable to the end, it will never work correctly, as you've already added the closing ".

So if you would like to take advantage of the string interpolation with c# 6 you could also do

var randomText = "insert something";
var yourString = $@"A bunch of text in here 
that is on seperate lines
but you want to {randomText }";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!