38

If I have a string variable that has:

"C:\temp\temp2\foo\bar.txt"

and I want to get

"foo"

what is the best way to do this?

6 Answers 6

79

Use:

new FileInfo(@"C:\temp\temp2\foo\bar.txt").Directory.Name
Sign up to request clarification or add additional context in comments.

5 Comments

According to msdn.microsoft.com/en-us/library/… the FileInfo constructor can throw if the caller does not have the required permission. Is there an alternative that will only parse the string without any IO ?
@GuiSim: Not that I'm aware of.
In case someone needs the full directory path, use new FileInfo(@"C:\temp\temp2\foo\bar.txt").DirectoryName instead.
String manipulation: var dir= _installPath.Split(new[]{Path.DirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries).Last();
I'm convinced that Google has some top secret Stack Overflow infiltration department and Jon Skeet is one of their highly trained operatives. There's no other way someone working at a demanding company like Google has this much free time to answer questions.
11

Far be it for me to disagree with the Skeet, but I've always used

Path.GetFileNameWithoutExtension(@"C:\temp\temp2\foo\bar.txt")

I suspect that FileInfo actually touches the file system to get it's info, where as I'd expect that GetFileNameWithoutExtension is only string operations - so performance of one over the other might be better.

5 Comments

There's a slight difference in results here... I think your approach returns "bar" when the question is asking how to get "foo" the file's containing directory...
I learned two things today... Read the question and never disagree with the Skeet.
Doesn't Path.getDirectoryName do exactly what he wants?
Path.GetDirectoryName would return "C:\temp\temp2\foo"
You could do Path.GetFileName(Path.GetDirectoryName(filepath)) - which in testing appears to do the job, and doesn't touch the filesystem.
9

I think most simple solution is

DirectoryInfo dinfo = new DirectoryInfo(path);

string folderName= dinfo.Parent.Name;

Comments

4

Building on Handleman's suggestion, you can do:

Path.GetFileName(Path.GetDirectoryName(path))

This doesn't touch the filesystem (unlike FileInfo), and will do what's required. This will work with folders because, as the MSDN says:

Return value: The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns String.Empty. If path is null, this method returns null.

Also, looking at the reference source confirms that GetFilename doesn't care if the path passed in is a file or a folder: it's just doing pure string manipulation.

Comments

2

I had an occasion when I was looping through parent child directories

string[] years = Directory.GetDirectories(ROOT);
foreach (var year in years)
{
    DirectoryInfo info = new DirectoryInfo(year);
    Console.WriteLine(info.Name);
    Console.WriteLine(year);
    //Month directories
    string[] months = Directory.GetDirectories(year);
    foreach (var month in months)
    {
        Console.WriteLine(month);
        //Day directories
        string[] days = Directory.GetDirectories(month);
        foreach (var day in days)
        {
            //checkes the files in the days
            Console.WriteLine(day);
            string[] files = Directory.GetFiles(day);
            foreach (var file in files)
            {
                Console.WriteLine(file);                               
            }
        }
    }
}

using this line I was able to get only the current directory name

DirectoryInfo info = new DirectoryInfo(year);
Console.WriteLine(info.Name);

Comments

1

It'll depend on how you want to handle the data, but another option is to use String.Split.

string myStr = @"C:\foo\bar.txt";
string[] paths = myStr.Split('\\');
string dir = paths[paths.Length - 2]; //returns "foo"

This doesn't check for an array out of bounds exception, but you get the idea.

2 Comments

That will fail on Linux.
Path.DirectorySeparatorChar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.