Reputation: 2483
I am building a windows explorer app for the web using ASP.NET/C# 3.5. I have a dynamic string that holds my path information. This string changes as you navigate the application. What I am trying to do is get the last “directory name” in my string so for example:
C:\Code\AppSettings
I would need to return AppSettings
If the string was:
C:\Code\AppSettings\Backup
Then I would need to return Backup
I am not savvy enough with string manipulation to get this correctly from a dynamic string. Any help or examples would be great.
Thanks!
Upvotes: 0
Views: 321
Reputation: 3666
I think this should do it:
exampleString = "C:\Code\AppSettings\Backup"
string[] words = exampleString.Split('\\');
Tokenises the string according to '\\'
i.e. will split the string at the '\'
symbol, into an array containing C:
Code
AppSettings
Backup
Then all you would need to do is use the last element in the words
list however you like.
I've never used Path
before, but i'm wondering whether it would get what you want, as the last part of the string may be a directory.
Upvotes: 0
Reputation: 70379
It is better to use Path class for handling this kind of stuff...
But if you want to it via string handling try
string myResult = myString.SubString (myString.LastIndexOf ( "\\") + 1 );
Upvotes: 0
Reputation: 56516
Path.GetFileName(@"C:\Code\AppSettings\Backup")
results in Backup
The System.IO.Path
should be used for file or directory path manipulations - it offers plenty of other useful methods.
Upvotes: 1
Reputation: 134045
Take a look at the Path class. In your case, Path.GetFileName
would work. Unless there's a trailing backslash. Then you'll need to strip that trailing backslash first.
Or, you can use Substring
or String.Split
as others have suggested. However, note that you have to take into account the possibility of that trailing backslash, which can cause trouble with any of the alternatives.
By trailing backslash, I mean a string like C:\Code\AppSettings\
.
Upvotes: 1
Reputation: 217351
Since you're dealing with file/directory paths, it's best to use the helper methods of the Path Class instead of string manipulation.
You can use the Path.GetFileName Method:
var result = Path.GetFileName(@"C:\Code\AppSettings");
// result == "AppSettings"
Upvotes: 5