【问题标题】:Getting files from my drive returns 0 in c#从我的驱动器获取文件在 C# 中返回 0
【发布时间】:2019-01-13 05:55:13
【问题描述】:

我只是 VS、C# 和 XAML 的新手。 我正在构建这个项目,我想在我的D;\ 驱动器中显示所有图像。所以我实际上是从这个question 得到这个代码的,幸运的是我可以毫无困难地工作。我可以告诉代码正在运行,因为我的应用程序现在需要大约 2 分钟才能启动,因此由于搜索到的图像而被延迟

public static IEnumerable<string> GetDirectoryFiles(string rootPath, string patternMatch, SearchOption searchOption)
{
    var foundFiles = Enumerable.Empty<string>();
    if (searchOption == SearchOption.AllDirectories)
    {
        try
        {
            IEnumerable<string> subDirs = Directory.EnumerateDirectories(rootPath);
            foreach (string dir in subDirs)
            {
                foundFiles = foundFiles.Concat(GetDirectoryFiles(dir, patternMatch, searchOption));
            }
        }
        catch (UnauthorizedAccessException) { }
        catch (PathTooLongException) { }
    }
    try
    {
        foundFiles = foundFiles.Concat(Directory.EnumerateFiles(rootPath, patternMatch));
    }
    catch (UnauthorizedAccessException) { }
    return foundFiles;
}

我用这行代码调用函数GetDirectoryFiles

string[] filePaths = {};
string[] extObj = { "*.JPG", ".JPEG", ".PNG", ".GIF", ".BMP*.jpg", ".jpeg", ".png", ".gif", ".bmp" };
foreach(var ext in extObj)
    filePaths.Concat(GetDirectoryFiles(@"D:\", ext, SearchOption.AllDirectories));
System.Diagnostics.Debug.WriteLine(filePaths.Length);

但是我遇到了一个问题...当filePaths.Length 输出时,我得到0。我实际上不知道为什么,但我知道我的D:\ 驱动器中至少有 4000 个.jpg 图像,所以我不应该得到 0。

简而言之我的问题:我想在我的D:\ 驱动器中加载所有图像,不包括返回UnauthorizedAccessExceptionPathTooLongException 错误的路径,参考我之前的question

【问题讨论】:

  • 您无缘无故地传递了两次相同的文件扩展名:搜索模式不区分大小写。您将获得两次相同的文件。这里还有一个类型:".BMP*.jpg"。看看这是否真的是一个错字。

标签: c#


【解决方案1】:

Concat 扩展方法返回一个新的可枚举对象,但您没有对它做任何事情。您需要将其分配回filePaths

首先,更改文件路径的类型。如果将其保留为数组,则每次都必须不断对其进行具体化(例如调用ToArray),而且代价高昂。

IEnumerable<string> filePaths = Enumerable.Empty<string>();

然后,将每个新的可枚举分配回 filePaths。

foreach (var ext in extObj)
    filePaths = filePaths.Concat(GetDirectoryFiles(@"D:\", ext, SearchOption.AllDirectories));

最后,filePaths 是IEnumerable&lt;string&gt;,所以你必须使用Count() 而不是Length

System.Diagnostics.Debug.WriteLine(filePaths.Count());

...或者只是具体化它...

string[] finalFilePaths = filePaths.ToArray();
System.Diagnostics.Debug.WriteLine(finalFilePaths.Length);

【讨论】:

    【解决方案2】:

    试试

        foreach(var ext in extObj)
            filePaths= filePaths.Concat(GetDirectoryFiles(@"D:\", ext, SearchOption.AllDirectories));
    

    您忘记将 concat 的结果分配给同一来源

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 2021-01-13
      • 1970-01-01
      • 2011-02-20
      相关资源
      最近更新 更多