how to handle spaces in file path if the folder co

2020-02-06 02:07发布

问题:

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 contains the file names like:

D:\Visual Studio Projects\ProjectOnTFS\ProjectOnTFS

Then I get the error:

回答1:

It'll need doubles quotes, but will also likely need an @ to treat the string word-for-word (verbatim string) i.e. the "\" has a special meaning in string e.g. \t means a tab, so we want to ignore the \

So not only the double quotes, but also @

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


回答2:

I use the following in most of my apps (if required) to add double quotes at the start and end of a string if there are white 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 empty string

AddQuotesIfRequired(null);

Returns empty string

EDIT

As per suggestion, changed the name of the function and also added a null reference check.

Added check to see if double quotes already exist at the start and end of string so not to duplicate.

Changed the string check function to IsNullOrWhiteSpace to check for white space as well as empty or null, which if so, will return an empty string.



回答3:

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

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

By escaping the back slashes you do not have to use the @ symbol. Just another alternative.