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?
Try,
Above line may throw UnauthorizedAccessException. To handle this check out below link
C# Handle System.UnauthorizedAccessException in LINQ
Have a look at using FileInfo.Name Property
something like
Also have a look at using DirectoryInfo Class and FileInfo Class
You can use
System.IO.Path.GetFileName
to do this.E.g.,
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 withGetFiles
unless you need the additional functionality of theFileInfo
class.Use this to obtain only the filename.