获取文件名不特定目录的路径 [英] Get filenames without path of a specific directory

查看:181
本文介绍了获取文件名不特定目录的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到一个目录(及其subdirectorys)的所有文件名不完整的路径? Directory.GetFiles(...)总是返回完整的路径!

How can I get all filenames of a directory (and its subdirectorys) without the full path? Directory.GetFiles(...) returns always the full path!

推荐答案

您可以提取完整路径文件名。

You can extract the filename from full path.

var filenames3 = Directory
                .GetFiles(dirPath, "*", SearchOption.AllDirectories)
                .Select(f => Path.GetFileName(f));

.NET 4中,文件名只

var filenames4 = Directory
                .EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
                .Select(Path.GetFileName); // <-- note you can shorten the lambda

返回目录中的文件名使用相对路径

// - file1.txt
// - file2.txt
// - subfolder1/file3.txt
// - subfolder2/file4.txt

var skipDirectory = dirPath.Length;
// because we don't want it to be prefixed by a slash
// if dirPath like "C:\MyFolder", rather than "C:\MyFolder\"
if(!dirPath.EndsWith("" + Path.DirectorySeparatorChar)) skipDirectory++;

var filenames4s = Directory
                .EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
                .Select(f => f.Substring(skipDirectory));

确认LinqPad ...

filenames3.SequenceEqual(filenames4).Dump(".NET 3 and 4 methods are the same?");

filenames3.Dump(".NET 3 Variant");
filenames4.Dump(".NET 4 Variant");
filenames4s.Dump(".NET 4, subfolders Variant");

注意 *文件(目录,模式,行为)方法可以简化非递归 *文件(目录) 的变种,如果子并不重要

Note that the *Files(dir, pattern, behavior) methods can be simplified to non-recursive *Files(dir) variants if subfolders aren't important

这篇关于获取文件名不特定目录的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆