views:

109

answers:

3

Hi

Here is some code

string path = "C:/folder1/folder2/file.txt";

What objects or methods could I use that would give me a result of folder2?

Thank you in advance.

+3  A: 
System.IO.Path.GetDirectoryName(path);
Zippit
That will return the entire path `C:/folder1/folder2`, not just the last directory name in the path.
LBushkin
+8  A: 

This should work:

FileInfo fileInfo = new FileInfo(path);
string folder = fileInfo.Directory.Name;

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.directory.aspx

http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.name.aspx

This Name property returns only the name of the directory, such as "Bin"

Dan Dumitru
This will work *only* if the path actually exists. Otherwise, see my answer.
LBushkin
@Dan, Also will return C:/folder1/folder2 instead of folder2
Michael Pakhantsov
@Michael - I've tested it, it works OK. It returns only the folder name, not the whole path.
Dan Dumitru
what reader asks is pure string manipulation. Why instantiate FileInfo for it? I really prefer LBushkin's answer
Andrey
@Dan, You are right I used DirectoryName instead of Directory.Name. :)
Michael Pakhantsov
@Andrey - I wouldn't be surprised if Path.GetDirectoryName() would instantiate a FileInfo object internally - but I'm just speculating.
Dan Dumitru
@Dan Dumitru no, you are wrong. take a Reflector and peek into Path class. Pure string manipulations.
Andrey
+8  A: 

I would probably use something like:

string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );

The inner call to GetDirectoryName will return the full path, while the outer call to GetFileName() will return the last path component - which will be the folder name.

This approach works whether or not the path actually exists. This approach, does however, rely on the path initially ending in a filename. If it's unknown whether the path ends in a filename or folder name - then it requires that you check the actual path to see if a file/folder exists at the location first. In that case, Dan Dimitru's answer may be more appropriate.

LBushkin