How to get file name in directory in c #

Directory.GetFiles(targetDirectory); 

Using the code above, we get the names ( i.e. the full path) of all the files in the directory. but I need to get only the file name, not the path. So, how can I get the name of only the files except the path? Or do I need to perform string operations when deleting an unwanted part?

EDIT:

 TreeNode mNode = new TreeNode(ofd.FileName, 2, 2); 

Here ofd is OpenFileDialog , and ofd.FileName indicates the name of the file along with Path, but I only need the file name.

+4
source share
3 answers

You can use:

 Path.GetFileName(fullPath); 

or in your example:

 TreeNode mNode = new TreeNode(Path.GetFileName(ofd.FileName), 2, 2); 
+13
source

Use DirectoryInfo and FileInfo if you want to get only file names without manual editing.

 DirectoryInfo dir = new DirectoryInfo(dirPath); foreach (FileInfo file in dir.GetFiles()) Console.WriteLine(file.Name); 
+3
source

Using:

  foreach(FileInfo fi in files) { Response.Write("fi.Name"); } 
+1
source

All Articles