Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of File in a directory in C#

Tags:

c#

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.

like image 584
SyncMaster Avatar asked Dec 03 '22 15:12

SyncMaster


2 Answers

You could use:

Path.GetFileName(fullPath);

or in your example:

TreeNode mNode = new TreeNode(Path.GetFileName(ofd.FileName), 2, 2);
like image 194
ChrisF Avatar answered Dec 06 '22 05:12

ChrisF


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);
like image 38
SO User Avatar answered Dec 06 '22 05:12

SO User