给定文件夹路径(如C:\Random Folder),如何在其中找到包含特定扩展名的文件(如txt )?我假设我必须在目录中搜索*.txt,但是我不确定首先应该如何开始搜索。
发布于 2010-07-01 02:21:50
看看System.IO.Directory类和静态方法GetFiles。它有一个接受路径和搜索模式的重载。示例:
string[] files = System.IO.Directory.GetFiles(path, "*.txt");发布于 2010-07-01 02:22:04
您可以使用Directory类
Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories)发布于 2010-07-01 02:24:29
实际上,这很容易。您可以将System.IO.Directory类与System.IO.Path结合使用。类似于(使用LINQ使其更容易):
var allFilenames = Directory.EnumerateFiles(path).Select(p => Path.GetFileName(p));
// Get all filenames that have a .txt extension, excluding the extension
var candidates = allFilenames.Where(fn => Path.GetExtension(fn) == ".txt")
.Select(fn => Path.GetFileNameWithoutExtension(fn));当然,这种技术也有很多不同的变体。如果你的过滤器更简单,其他一些答案也会更简单。这种方法的优点是延迟枚举(如果这很重要)和更灵活的过滤,但代价是需要更多的代码。
https://stackoverflow.com/questions/3152157
复制相似问题