Click here to Skip to main content
15,889,849 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If the actual folder names are unknown how could i then only get the last index text in this example only get Sub2?
\\Sub1\\Sub2\\

In this example
\\Sub1\\Sub2\\Sub3\\
Only get Sub3 ?
Posted

use DirectoryInfo.Name Property.

C#
string str = @"\sub1\sub2\sub3";
string dirName = new DirectoryInfo(str).Name;

ref.
https://msdn.microsoft.com/en-us/library/system.io.directoryinfo.name.aspx[^]
http://stackoverflow.com/questions/5229292/get-folder-name-from-full-file-path-c-asp-net[^]
 
Share this answer
 
Comments
CHill60 9-Feb-15 6:29am    
5'd. Nice and elegant. Kurac1 - you will need "using System.IO;"
/\jmot 9-Feb-15 12:41pm    
thank you. :)
You have given yourself a clue in your question - use strng.LastIndexOf[^] method.

For example:

C#
string str = @"\sub1\sub2\sub3";
var x = str.LastIndexOf('\\');
Console.WriteLine(str.Substring(x + 1, str.Length - x - 1));
 
Share this answer
 
Comments
Kurac1 9-Feb-15 6:07am    
i dont get the value in debug it gets "" (empty)
CHill60 9-Feb-15 6:29am    
When I run it, it works fine. Can you post the code you used?
Use string.Split on "\\" with stringsplitoption "RemoveEmptyEntries".
Then you can fetch last item of string array.
For e.g.
C#
string[] s = "\\Sub1\\Sub2\\Sub3\\".Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);


Then your desired string would be in
C#
s[s.Length - 1];
 
Share this answer
 
Comments
Kurac1 9-Feb-15 6:04am    
i dont get the value in debug it gets "" (empty)
CHill60 9-Feb-15 6:29am    
When I run this one, it also works fine - post the code you used for this too

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900