Reputation: 1899
Here is my code
string path1 = @"C:\Program Files (x86)\Common Files";
string path2 = @"Microsoft Shared";
string path = Path.Combine(path1, path2);
Console.WriteLine(path);
The output provides me
C:\Program Files (x86)\Common Files\Microsoft Shared
I would like to have any folder names with spaces in double quotes as follows
C:\"Program Files (x86)"\"Common Files"\"Microsoft Shared"
How can I get that?
Upvotes: 0
Views: 1785
Reputation: 883
The easiest way to do this would be with LINQ.
You can split your folder path into an array listing all of the folder names, then manipulate each individual element using a Select()
.
In your case you would want to:
"{folderName}"
if the folder name contains spacesHere is what that would look like, please note I have used 2 Select()
's for clarity & to help identify the different steps. They can be a single statement.
string path1 = @"C:\Program Files (x86)\Common Files";
string path2 = @"Microsoft Shared";
string path = System.IO.Path.Combine(path1, path2);
var folderNames = path.Split('\\');
folderNames = folderNames.Select(fn => (fn.Contains(' ')) ? String.Format("\"{0}\"", fn) : fn)
.ToArray();
var fullPathWithQuotes = String.Join("\\", folderNames);
The output of the above process is:
C:\"Program Files (x86)"\"Common Files"\"Microsoft Shared"
Upvotes: 2
Reputation: 20754
You can create an extension method
public static class Ex
{
public static string PathForBatchFile(this string input)
{
return input.Contains(" ") ? $"\"{input}\"" : input;
}
}
use it like
var path = @"C:\Program Files (x86)\Common Files\Microsoft Shared";
Console.WriteLine(path.PathForBatchFile());
It uses the string interpolation feature in C# 6.0. If you are not using C# 6.0 you can use this instead.
public static class Ex
{
public static string PathForBatchFile(this string input)
{
return input.Contains(" ") ? string.Format("\"{0}\"", input) : input;
}
}
Upvotes: 1