[ACCEPTED]-Split path by "\\" in C#-split
You should be using
path.Split(Path.DirectorySeparatorChar);
if you're trying to split 1 a file path based on the native path separator.
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 :)
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.
To be on the safe side, you could use:
path.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
0
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.
Path.Split(new char[] { '\\\' });
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.