Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

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

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 estfile.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = @"\serversharedirectory 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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...