1

我正在尝试.mp3从多个文件夹中获取文件。

我已经可以通过此查询为一个文件夹执行此操作:

this.MusicList.ItemsSource =
                from string fileName in Directory.GetFiles(@"C:\Users\Public\Music\Sample Music")
                where System.IO.Path.GetExtension(fileName) == ".mp3"
                select new FileInfo(fileName);

对于目录列表还有其他方法吗?

这是我迄今为止尝试过的(没有返回结果):

var paths = new Dictionary<string, string> {
            {"default_music", @"C:\Users\Public\Music\Sample Music"},
            {"alternative_folder", @"C:\tmp"}
            };

this.MusicList.ItemsSource = 
from string fileName in (from string directoryName in paths.Values select Directory.GetFiles(directoryName))
where System.IO.Path.GetExtension(fileName) == ".mp3"
select new FileInfo(fileName);

from string directoryName in paths.Values select Directory.GetFiles(directoryName);在其字段中返回{System.Linq.Enumerable.WhereSelectEnumerableIterator<string,string[]>}带有我的路径及其包含我的文件的 a。sourceResult View.mp3

谢谢

4

4 回答 4

6

尝试以下

this.MusicList.ItemsSource =
  from path in paths
  from fileName in Directory.GetFiles(path)
  where System.IO.Path.GetExtension(fileName) == ".mp3"
  select new FileInfo(fileName);

严格方法调用版本

this.MusicList.ItemSource = paths
  .SelectMany(path => Directory.GetFiles(path))
  .Where(fileName => System.IO.Path.GetExtension(fileName) == ".mp3")
  .Select(fileName => new FileInfo(fileName));
于 2013-03-06T16:12:39.957 回答
3

您可以使用接受搜索模式的DirectoryInfo.EnumerateFiles方法。因此,您不需要获取所有文件并通过调用过滤它们Path.GetExtension

var paths = new Dictionary<string, string> {
        {"default_music", @"C:\Users\Public\Music\Sample Music"},
        {"alternative_folder", @"C:\tmp"}
     };

MusicList.ItemsSource = paths.Values.Select(p => new DirectoryInfo(p))
                             .SelectMany(d => d.EnumerateFiles("*.mp3"));

DirectoryInfo.EnumerateFiles返回FileInfo实例,这也是你想要的。

于 2013-03-06T16:17:33.937 回答
1

试试这个

Directory.EnumerateFiles(@"C:\Users\Public\Music\Sample Music", "*.mp3", SearchOption.AllDirectories)

返回 .mp3 的可枚举列表,您可以进一步过滤或枚举等。这比GetFiles()处理大量文件和/或目录更有效。

http://msdn.microsoft.com/en-us/library/dd383571.aspx

于 2013-03-06T16:17:16.283 回答
0

替代跟踪它是否是文件/目录的可敬的 JaredPar:

var basePath = @"c:\temp";
var query = 
    from entry in Directory.EnumerateFileSystemEntries(basePath, "*.*", SearchOption.AllDirectories)
    let isDirectory = Directory.Exists(entry)
    let isFile = File.Exists(entry)
    select new { isDirectory, isFile, entry};
query.Dump();

编辑:Doh - 误读问题,错过了“来自一组目录”部分;我的耻辱是无法估量的。:)

于 2013-03-06T16:15:58.343 回答