Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.GetFiles: how to get only filename, not full path? [duplicate]

Possible Duplicate:
How to get only filenames within a directory using c#?

Using C#, I want to get the list of files in a folder.
My goal: ["file1.txt", "file2.txt"]

So I wrote this:

string[] files = Directory.GetFiles(dir); 

Unfortunately, I get this output: ["C:\\dir\\file1.txt", "C:\\dir\\file2.txt"]

I could strip the unwanted "C:\dir\" part afterward, but is there a more elegant solution?

like image 462
Nicolas Raoul Avatar asked Sep 21 '12 04:09

Nicolas Raoul


People also ask

How do I extract just the filename?

You simple just reference the passing in or dragged and dropping of the file name as %~nx1 .... Specifically %~nx1 will give you the file name and extension only.

How to get file name in directory C#?

The Directory. GetFiles() method in C# gets the names of all the files inside a specific directory. The Directory. GetFiles() method returns an array of strings that contains the absolute paths of all the files inside the directory specified in the method parameters.

How to get the path of a file in a directory?

You can use System.IO.Path.GetFileName to do this. string [] files = Directory.GetFiles (dir); foreach (string file in files) Console.WriteLine (Path.GetFileName (file)); While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths).

Do file names include the full path of the file?

The file names include the full path. The path parameter can specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

How to get only the filename of a file in C++?

string [] files = Directory.GetFiles (dir); for (int iFile = 0; iFile < files.Length; iFile++) string fn = new FileInfo (files [iFile]).Name; Use this to obtain only the filename.

What does ‘Directory getfiles(path)’ mean?

But what does ‘directory.getfiles (path,". ")’ mean? Directory. GetFiles is a Fuction the Used to fetch the Files From the Folders. Directory -->Specfies Your Folder.


1 Answers

You can use System.IO.Path.GetFileName to do this.

E.g.,

string[] files = Directory.GetFiles(dir); foreach(string file in files)     Console.WriteLine(Path.GetFileName(file)); 

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

like image 176
D'Arcy Rittich Avatar answered Sep 21 '22 00:09

D'Arcy Rittich