Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get .NET's Path.Combine to convert forward slashes to backslashes?

Tags:

c#

.net

I'm using Path.Combine like so:

Path.Combine("test1/test2", "test3\\test4"); 

The output I get is:

test1/test2\test3\test4 

Notice how the forward slash doesn't get converted to a backslash. I know I can do string.Replace to change it, but is there a better way of doing this?

like image 771
Daniel T. Avatar asked Jun 29 '10 20:06

Daniel T.


People also ask

How do you change forward slash to backward slash?

Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.

What is the difference between forward slashes and backslashes?

Summary: The Backslash and Forward SlashThe backslash (\) is mostly used in computing and isn't a punctuation mark. The forward slash (/) can be used in place of “or” in less formal writing. It's also used to write dates, fractions, abbreviations, and URLs.

Why do Windows use backslashes paths?

The reason Microsoft is backwards on this goes back to MS-DOS 2.0 (DOS 1.0 had no directory hierarchy), which used a backslash to stay compatible with Dos 1.0 commands, which used slash for command line switches.


1 Answers

As others have said, Path.Combine doesn't change the separator. However if you convert it to a full path:

Path.GetFullPath(Path.Combine("test1/test2", "test3\\test4")) 

the resulting fully qualified path will use the standard directory separator (backslash for Windows).

Note that this works on Windows because both \ and / are legal path separators:

Path.DirectorySeparatorChar = \ Path.AltDirectorySeparatorChar = / 

If you run on, say, .NET Core 2.0 on Linux, only the forward slash is a legal path separator:

Path.DirectorySeparatorChar = / Path.AltDirectorySeparatorChar = / 

and in this case it won't convert backslash to forward slash, because backslash is not a legal alternate path separator.

like image 78
Joe Avatar answered Oct 04 '22 20:10

Joe