tags:

views:

3925

answers:

5

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?

+19  A: 

Use new FileInfo(@"C:\temp\temp2\foo\bar.txt").Directory.Name

Jon Skeet
A: 

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.

Handleman
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...
Kit Roed
I learned two things today... Read the question and never disagree with the Skeet.
Handleman
Doesn't Path.getDirectoryName do exactly what he wants?
Charlie boy
A: 

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

            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);
Shameegh Boer
A: 

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.

RodYan
A: 

I think most simple solution is

DirectoryInfo dinfo = new DirectoryInfo(path);

string folderName= dinfo.Parent.Name;

Ananth