Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - Get filenames without path of a specific directory

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can extract the filename from full path.

.NET 3, filenames only

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

.NET 4, filenames only

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

Return filenames with relative path inside the directory

// - 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));

confirm in 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...