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.