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

烈酒焚心 提交于 2019-11-28 12:22:09

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";

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.

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.

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