Reputation: 123
I am trying to get the 2nd to last level of the directory tree that I used an array to get. When it gets to the Console.WriteLine part, it doesn't display anything, it seems to skip that entire line.
foreach (string file in files)
{
string thepathoflife = Path.GetFullPath(file);
string filetocopy = file;
string location = file;
bool b = false;
string extension = Path.GetExtension(file);
string thenameofdoom = Path.GetFileNameWithoutExtension(file);
string filename = Path.GetFileName(file);
//here is my attempt
string dirthing = Path.GetDirectoryName(filename); //here is my attempt
System.Console.WriteLine("" + dirthing); //here is my attempt
Upvotes: 1
Views: 1134
Reputation: 217371
Here are a few examples:
var path = Path.GetFullPath("example.png");
// path == "C:\\Users\\dtb\\Desktop\\example.png"
Path.GetFileName(path) // "example.png"
Path.GetFileNameWithoutExtension(path) // "example"
Path.GetExtension(path) // ".png"
Path.GetDirectoryName(Path.GetFileName(path)) // ""
Path.GetDirectoryName(path) // "C:\\Users\\dtb\\Desktop"
Path.GetDirectoryName(Path.GetDirectoryName(path)) // "C:\\Users\\dtb"
Upvotes: 2
Reputation: 106916
You can call Path.GetDirectoryName
twice to walk up the folder hierarchy:
Path.GetDirectoryName(Path.GetDirectoryName(Path.GetFullPath(file)))
It will return null
if you are too "high" in the hierarchy.
Upvotes: 3