Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...