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?
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?
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.
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);
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.
I think most simple solution is
DirectoryInfo dinfo = new DirectoryInfo(path);
string folderName= dinfo.Parent.Name;