【问题标题】:Retrieve all pdf files that exist in My Computer检索“我的电脑”中存在的所有 pdf 文件
【发布时间】:2014-04-09 15:23:22
【问题描述】:

我有以下代码可以从 MyComputer 中检索所有 pdf 文件。但我收到如下错误。是否可以使用 C# 代码从一台计算机上检索所有 pdf 文件。

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);            
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path); // Error : The path is not of a legal form.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.pdf", System.IO.SearchOption.AllDirectories);

【问题讨论】:

  • path 传递给DirectoryInfo 构造函数时的值是多少?
  • 错误只是说,您指定了非法路径。
  • 您需要查看所有驱动器(请参阅stackoverflow.com/questions/781905/…),并在子文件夹中递归
  • 我将路径设置为 MyComputer 文件夹/目录。字符串路径 = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
  • 路径以“”的形式出现。所以它会引发错误。为什么路径对我来说是空的?

标签: c# c#-4.0 filesystems .net


【解决方案1】:

您可以获取所有驱动器,然后获取所有文件。

编辑:您还可以使用Directory.EnumerateFiles 方法,它可以让您获取文件路径,您可以将其添加到您的列表中。这将为您提供所有文件路径的List&lt;string&gt;。喜欢:

List<string> filePathList = new List<string>();
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    try
    {
        var filenames = Directory.EnumerateFiles(drive.Name, "*.pdf", SearchOption.AllDirectories);
        foreach (string fileName in filenames)
        {
            filePathList.Add(fileName);
        }
    }
    catch (FieldAccessException ex)
    {

        //Log, handle Exception
    }
    catch (UnauthorizedAccessException ex)
    {
        //Log, handle Exception
    }
    catch (Exception ex)
    {
        //log , handle all other exceptions
    }
}

旧答案。

List<FileInfo> fileList = new List<FileInfo>();
foreach (var drive in System.IO.DriveInfo.GetDrives())
{
    try
    {
        DirectoryInfo dirInfo = new DirectoryInfo(drive.Name);
        foreach (var file in dirInfo.GetFiles("*.pdf", SearchOption.AllDirectories))
            fileList.Add(file);

    }
    catch (FieldAccessException ex)
    {

        //Log, handle Exception
    }
    catch (UnauthorizedAccessException ex)
    {
        //Log, handle Exception
    }
    catch (Exception ex)
    {
        //log , handle all other exceptions
    }
}

【讨论】:

  • 我已经尝试过您的代码,但出现错误。错误:“访问路径 'C:\$Recycle.Bin\blahblah...\' 被拒绝”
  • @user3366358,针对该错误进行了修改,请检查答案的编辑部分。
  • 您的旧答案出现以下错误。出现此错误后,代码跳到我的 C 盘中搜索。 System.IO.Exception 设备未准备好。在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
  • @user3366358,您可以在DriveInfo.IsReady 属性上过滤您的驱动器
  • 这是完美的。我还有一个问题,如果我想获取此列表中特定搜索词的 pdf 文件。所有驱动器搜索都花费了太多时间。我使用了 WMI SystemIndex,它有时不会返回即时添加的文件。
【解决方案2】:

您可以使用System.IO.DriveInfo 类循环访问机器上所有可用的驱动器(调用 DriveInfo.GetDrives() 以获取所有驱动器的列表)。您可能必须为每个驱动器执行此操作,并结合所有驱动器的结果。我对您当前代码的问题的猜测是,给它 MyComputer 文件夹不足以告诉它循环遍历所有驱动器。

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 2018-01-28
    • 2021-06-13
    • 2021-03-03
    相关资源
    最近更新 更多