How do you handle spaces in variables when using C# interpolation?

北城余情 提交于 2020-01-06 05:40:44

问题


With string interpolation, how do you handle variables piped into a command that contain spaces in them? For example, if you have a variable that has spaces in it (like a UNC path), how do you handle that?

This code works when no spaces are present in the "filePath" variable (i.e.; \ServerName\testfile.txt):

System.Diagnostics.Process.Start("net.exe", $"use X: \\{filePath} {pwd /USER:{usr}").WaitForExit();

As soon as you encounter a path that has spaces in it, however, the command above no longer works, because it's unable to find the path. Normally, I would apply quotes around a path containing spaces, to counter this (in other languages like PowerShell). How do you do something similar with C# interpolation.


回答1:


You would do this in c# just the way you would in the command line

System.Diagnostics.Process.Start("net.exe", $"use X: \"\\{filePath}\" {pwd /USER:{usr}").WaitForExit();



回答2:


It doesn't have anything to do with string interpolation, it has to do with how the executable parses the command line. Single arguments that have spaces in them (like a path) should be wrapped in quotes so they're treated as one argument and not several.

You can add quotes inside a string by escaping the quote character with a backslash character (\"):

var filePath = @"\\server\share\directory with spaces";
var usr = $"{Environment.UserDomainName}\\{Environment.UserName}";

System.Diagnostics.Process
    .Start("net.exe", $"use X: \"{filePath}\" pwd /USER:{usr}")
    .WaitForExit();

This is also true without string interpolation:

System.Diagnostics.Process
    .Start("net.exe", string.Format("use X: \"{0}\" pwd /USER:{1}", filePath, usr))
    .WaitForExit();


来源:https://stackoverflow.com/questions/50009781/how-do-you-handle-spaces-in-variables-when-using-c-sharp-interpolation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!