[ACCEPTED]-Split path by "\\" in C#-split

Accepted answer
Score: 36

You should be using


if you're trying to split 1 a file path based on the native path separator.

Score: 8

Try path.Split('\\') --- so single quote (for character)

To 3 use a string this works:

path.Split(new[] {"\\"}, StringSplitOptions.None)

To use a string 2 you have to specify an array of strings. I 1 never did get why :)

Score: 7

There's no string.Split overload which takes a string. (Also, C# is 16 case-sensitive, so you need Split rather than 15 split). However, you can use:

string bits = path.Split('\\');

which will use the 14 overload taking a params char[] parameter. It's equivalent 13 to:

string bits = path.Split(new char[] { '\\' });

That's assuming you definitely want to 12 split by backslashes. You may want to split 11 by the directory separator for the operating 10 system you're running on, in which case 9 Path.DirectorySeparatorChar would probably be the right approach... it 8 will be / on Unix and \ on Windows. On the 7 other hand, that wouldn't help you if you 6 were trying to parse a Windows file system 5 path in an ASP.NET page running on Unix. In 4 other words, it depends on your context 3 :)

Another alternative is to use the methods 2 on Path and DirectoryInfo to get information about paths 1 in more file-system-sensitive ways.

Score: 6

To be on the safe side, you could use:

path.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });


Score: 1

On windows, using forward slashes is also 9 accepted, in C# Path functions and on the 8 command line, in Windows 7/XP at least.

e.g.: Both 7 of these produce the same results for me:

dir "C:/Python33/Lib/xml"
dir "C:\Python33\Lib\xml"
(In C:)
dir "Python33/Lib/xml"
dir "Python33\Lib\xml"

On 6 windows, neither '/' or '\' are valid chars 5 for filename. On Linux, '\' is ok in filenames, so 4 you should be aware of this if parsing for 3 both.

So if you wanted to support paths in 2 both forms (like I do) you could do:

path.Split(new char[] {'/', '\\'});

On Linux 1 it would probably be safer to use Path.DirectorySeparatorChar.

Score: 0
Path.Split(new char[] { '\\\' });


Score: 0

Better just use the existing class System.IO.Path, so 3 you don't need to care for any system specifications.

It 2 provides methods to access any part of a 1 file path like GetFileName(string path) etc.

More Related questions