How to handle spaces in the file path if the folder contains a space?

public static void launchProcess(string processName, string arguments, out string output) { Process p = new Process { StartInfo = { UseShellExecute = false, RedirectStandardOutput = true, FileName = processName, Arguments = arguments } }; p.Start(); output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); } 

And if my arguments contain file names, for example:

 D:\Visual Studio Projects\ProjectOnTFS\ProjectOnTFS 

Then I get the error message:

+4
source share
3 answers

This will require double quotes, but also probably need @ to process the word by word ( verbatim string ) i.e. "\" has a special meaning in the string, for example \ t means tab, so we want to ignore \

Thus, not only double quotes, but also @

 string myArgument = @"D:\Visual Studio Projects\ProjectOnTFS\ProjectOnTFS"; 
+10
source

In most of my applications (if required) I use the following words: add double quotes at the beginning and end of the line if there are spaces.

 public string AddQuotesIfRequired(string path) { return !string.IsNullOrWhiteSpace(path) ? path.Contains(" ") && (!path.StartsWith("\"") && !path.EndsWith("\"")) ? "\"" + path + "\"" : path : string.Empty; } 

Examples ..

 AddQuotesIfRequired(@"D:\Visual Studio Projects\ProjectOnTFS\ProjectOnTFS"); 

Returns "D:\Visual Studio Projects\ProjectOnTFS\ProjectOnTFS"

 AddQuotesIfRequired(@"C:\Test"); 

Returns C:\Test

 AddQuotesIfRequired(@"""C:\Test Test\Wrap"""); 

Returns "C:\Test Test\Wrap"

 AddQuotesIfRequired(" "); 

Returns an empty string

 AddQuotesIfRequired(null); 

Returns an empty string

EDIT

According to the proposal, the name of the function has changed, and a null check has been added.

A check was added to see if double quotes exist at the beginning and end of a line so as not to duplicate.

Changed the function of checking the string in IsNullOrWhiteSpace to check the space, as well as an empty or null value, which, if so, will return an empty string.

+5
source

I understand that this is an old thread, but for people who see it after me, you can also do:

 string myArgument="D:\\Visual Studio Projects\\ProjectOnTFS\\ProjectOnTFS" 

While holding back slashes, you do not need to use the @ character. Another alternative.

+2
source

All Articles