目录。 GetFiles: 如何只获得文件名,而不是完整的路径?

可能的复制品:
如何使用 c # 只获取目录中的文件名?

使用 C # ,我想得到一个文件夹中的文件列表。
我的目标: ["file1.txt", "file2.txt"]

所以我写道:

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

不幸的是,我得到了这个输出: ["C:\\dir\\file1.txt", "C:\\dir\\file2.txt"]

之后我可以去掉不需要的“ C: dir”部分,但是有没有更优雅的解决方案呢?

240672 次浏览

Have a look at using FileInfo.Name Property

something like

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


for (int iFile = 0; iFile < files.Length; iFile++)
string fn = new FileInfo(files[iFile]).Name;

Also have a look at using DirectoryInfo Class and FileInfo Class

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.

Use this to obtain only the filename.

Path.GetFileName(files[0]);

Try,

  string[] files =  new DirectoryInfo(dir).GetFiles().Select(o => o.Name).ToArray();

Above line may throw UnauthorizedAccessException. To handle this check out below link

C# Handle System.UnauthorizedAccessException in LINQ