3

I have file name which look like

Directory\name-secondName-blabla.txt

If I using string .split my code need to know the separator I am using, But if in some day I will replace the separator my code will break

Is the any build in way to split to get the following result?

Directory
name
secondNmae
blabla
txt

Thanks

Edit My question is more general than just split file name, is splitting string in general

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
user956962
  • 33
  • 6
  • Couldn't you just use a function that calls split and whose one of its arguments is the separator? – Mansuro Sep 21 '11 at 12:51
  • 1
    Man, try to search a little SO: http://stackoverflow.com/questions/2742688/getting-file-name-from-the-string http://stackoverflow.com/questions/1105593/get-file-name-from-uri-string-in-c http://stackoverflow.com/questions/401304/c-how-do-i-extract-each-folder-name-from-a-path http://stackoverflow.com/questions/3736462/c-getting-the-folder-name-from-a-path – Samich Sep 21 '11 at 12:51
  • 2
    I think everyone seems to have not read this question properly! – Tim B James Sep 21 '11 at 12:53
  • 2
    It seems that no one read my Edit also – user956962 Sep 21 '11 at 13:01
  • "[when] I will replace the separator my code will break" - Yes, it ususally does. You'll have to give a more detailed scenario. – H H Sep 21 '11 at 13:20

5 Answers5

8

The best way to split a filename is to use System.IO.Path

You're not clear about what to do with directory1\directory2\ ,
but in general you should use this static class to find the path, name and suffix parts.

After that you will need String.Split() to handle the - separators, you'll just have to make the separator(s) a config setting.

H H
  • 263,252
  • 30
  • 330
  • 514
2

You can make an array with seperators:

string value = "Directory\name-secondName-blabla.txt";
char[] delimiters = new char[] { '\\', '-', '.' };
string[] parts = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
Metaller
  • 504
  • 3
  • 10
0
var filepath = @"Directory\name-secondName-blabla.txt";
var tokens = filepath.Split(new[]{'\\', '-'});
fjdumont
  • 1,517
  • 1
  • 9
  • 22
0

If you're worried about your separator token changing in the future, set it as a constant in a settings file so you only have to change it in one place. Or, if you think it is going to change regularly, put it in a config file so you don't have to release new builds every time.

JHolyhead
  • 984
  • 4
  • 8
0

As Henk suggested above, use System.IO.Path and its static methods like GetFileNameWithoutExtenstion, GetDirectoryName, etc. Have a look at this link: http://msdn.microsoft.com/en-us/library/system.io.path.aspx

Huske
  • 9,186
  • 2
  • 36
  • 53