Help getting a directory name from a path

  • Thread starter Thread starter SimonH
  • Start date Start date
S

SimonH

Hi all,

I'm having problems identifying how to get the last directoy in a path string.

For example, in the Path 'C:\dir1\dir2\dir3'

I want to be able to get the name dir3

I've tried the following but for some reason it doesnt split the string at
all. It just returns the full string.

string[] splitPath = fullPath.Split('\\');

if(splitPath != null && splitPath.Length > 0){
dirName = splitPath[splitPath.Length - 1];
}

return dirName;

Ideally I'd also like to be able to identify the filename in a full path
string aswell, but I dont know how to do that either

Many thanks to anyone who could provide the magic incantations

Kindest Regards

Simon
 
I'd suggest that you should start with the Path class:
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemIOPathClassTopic.asp

As far as your Split statement goes, the following snippet works for me:

string MyPath = @"c:/temp/second/third/myfile.txt";
string[] parts = MyPath.Split('/');
foreach (string part in parts)
Console.WriteLine(part);

HTH,
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
Your code is fine. The problem lies with the contents of fullpath. How are
you populating fullpath? Run the following code to verify the same.

string[] fullPath=Directory.GetDirectories("c:\\");
string dirName="";
string[] splitPath = fullPath[0].Split('\\');
if(splitPath != null && splitPath.Length > 0)
{
dirName = splitPath[splitPath.Length - 1];
}
 
Hi, the problem lies in how you are populating fullpath. Check the following
code which works fine.

string[] fullPath=Directory.GetDirectories("c:\\");
string dirName="";
string[] splitPath = fullPath[0].Split('\\');
if(splitPath != null && splitPath.Length > 0)
{
dirName = splitPath[splitPath.Length - 1];
}
 
Back
Top