Reputation: 9916
Directory.GetFiles(targetDirectory);
Using the above code we get the names(i.e full path) of all the files in the directory. but i need to get only the name of the file and not the path. So how can I get the name of the files alone excluding the path? Or do I need to do the string operations in removing the unwanted part?
EDIT:
TreeNode mNode = new TreeNode(ofd.FileName, 2, 2);
Here ofd
is a OpenFileDialog
and ofd.FileName
is giving the the filename along with it's Path but I need the file name alone.
Upvotes: 4
Views: 16816
Reputation: 137108
You could use:
Path.GetFileName(fullPath);
or in your example:
TreeNode mNode = new TreeNode(Path.GetFileName(ofd.FileName), 2, 2);
Upvotes: 14
Reputation: 23788
Use DirectoryInfo and FileInfo if you want to get only the filenames without doing any manual string editing.
DirectoryInfo dir = new DirectoryInfo(dirPath);
foreach (FileInfo file in dir.GetFiles())
Console.WriteLine(file.Name);
Upvotes: 3