I have found that using Path.GetFileName() in the code below works as I intend and gives me the name of the correct folder, but if I use Path.GetDirectoryName() it returns the name of the parent (UserGeneratedContent) folder instead. Why does this occur when both methods are passed the same path as a string? And why does Path.GetFileName() work on directories?
When I use Path.GetFileName() the text of the nodes in the Treeview are those of the folders it finds – this is what I want to happen, but if I use Path.GetDirectoryName() the text is the full path from @”UserGeneratedContent” on down for each node. Why does that happen?
And lastly, can my code be improved?
private void CheckForBaseFolder()
{
if (Directory.Exists(@"UserGeneratedContent"))
{
DirectoryInfo info = new DirectoryInfo(@"UserGeneratedContent");
DirectoryInfo[] subdirs = info.GetDirectories();
if (subdirs.Length != 0)
{
string path = Path.Combine(@"UserGeneratedContent", subdirs[0].ToString());
treeView1.Nodes.Add(CheckForSubFolders(path));
treeView1.SelectedNode = treeView1.Nodes[0];
}
else { MessageBox.Show("No User-Generated Folders Or Files Found"); }
}
else { Directory.CreateDirectory(@"UserGeneratedContent"); }
}
private TreeNode CheckForSubFolders(string path)
{
TreeNode folder = new TreeNode(path);
folder.Text = Path.GetFileName(path); // Works as intended, but.....
folder.Text = Path.GetDirectoryName(path); // Returns the parent folder
foreach(var subdirectory in Directory.GetDirectories(path))
{
folder.Nodes.Add(CheckForSubFolders(subdirectory));
}
folder.ImageIndex = 0;
folder.SelectedImageIndex = 1;
return folder;
}
Check your code, you are passing the path that doesn’t contain filename but the last part of the path is directory UserGeneratedContent.
Path.GetFileNamereturns the “The characters after the last directory character in path” so it retuns the last directory name instead of filename (you can make a file without extension). When you callPath.GetDirectoryName()on the same path string it returns “Directory information for path”.Check this code to see what I’m referring to:
Suppose you have directory “one” on C partition, and directory “two” in directory “one”, and a file named “three.txt” in directory “two”, when you execute this code it will produce:
directorywill hold first “two” and then “C:\one”but now,
filenamewill hold “three.txt” anddirectorywill hold “C:\one\two”EDIT:This is later edit after the comments. I would modify the
CheckForSubFoldersmethod this way: