leora
leora

Reputation: 196791

get directory from full path

If i have:

C:\temp\foo\bar\

(NOTE: bar is a directory)

how can i parse out:

bar

Upvotes: 24

Views: 39321

Answers (10)

Razvan
Razvan

Reputation: 11

string dirname = new DirectoryInfo(path).Name;  
Console.WriteLine(dirname);   

Upvotes: 1

Matthew M.
Matthew M.

Reputation: 3482

The simplest way to do this without creating a new DirectoryInfo instance is to use the Path.GetFileName static method. This is located in System.IO.

using System.IO;

string lastFolderName = Path.GetFileName(@"C:\Folder1\Folder2");

The variable would be set to "Folder2".

This is quite a bit more efficient that creating a new instance of the DirectoryInfo class!

Upvotes: 6

Norbert B.
Norbert B.

Reputation: 5728

Just use:

string dirname = new DirectoryInfo(@"C:\temp\foo\bar\").Name;      

According to MSDN this returns the name of the directory, not the full path.

Link to MSDN Library

Hope this helps.........

Upvotes: 11

leora
leora

Reputation: 196791

I figured it out.

DirectoryInfo info = new DirectoryInfo(sourceDirectory_);
string currentDirectoryName = info.Name;

Upvotes: 45

Program.X
Program.X

Reputation: 7412

Try

System.IO.Path.GetFileName("C:\\temp\\foo\\bar");

Upvotes: 21

Anuraj
Anuraj

Reputation: 19608

Try this

string DirName = System.IO.Directory.GetParent(@"C:\temp\foo\bar\").Name;

Upvotes: 0

Chris S
Chris S

Reputation: 65456

I can think of 4 ways instantly

1

  • If the string ends with a slash remove it
  • Use Path.GetFilename (or numerous other System.IO methods)

2

  • Split the string on slashes into an array
  • Get the last index of the array

3

  • Create a Uri class with it in the constructor
  • Use the Segments property

4

  • The linq way someone mentioned above

Upvotes: 4

Daniel Earwicker
Daniel Earwicker

Reputation: 116724

It looks like a bunch of people have withdrawn their answers, which is possibly a shame.

This one's got to be worth stating, only for the "teach a man to fish" quality of it - it's short, elegant and made of two separate things that, once learned, can be re-applied to other problems.

string lastPiece = wholePath.Split('\\').Last();

Last will throw if the list is empty.

Upvotes: 7

Wim Haanstra
Wim Haanstra

Reputation: 5998

if the answers above do not satisfy your needs, why not just substring the string from the last .

string dirName = originalDirName.Substring(originalDirName.LastIndexOf("\\") + 1);

sure, you should do some checking if the originalDirName does not end on a \ and if the originalDirName is longer than zero and actually contains \ characters.

Upvotes: 0

MrTelly
MrTelly

Reputation: 14875

In Unix this is known as the basename, a quick google came up with this link for a C# version. I'm sure there are others ...

Upvotes: 0

Related Questions