首页 > 解决方案 > 循环遍历目录中的每个 PDF 文件

问题描述

我需要将每个文件上传到我们的文件管理系统。我正在尝试创建一个循环来访问每个 PDF 文件,然后执行上传。我最终陷入了混乱。任何提示如何正确地做到这一点?

这是我的烂摊子:

        string filepath = Path.GetFullPath(@"C:\temp\");

        DirectoryInfo d = new DirectoryInfo(filepath);

        var pdfPath = @"C:\temp\";
        var pdfFiles = new DirectoryInfo("C:\\temp\\").GetFiles("*.pdf");
        var PdfFilename = pdfFiles[0].Name;

        var destinationFile = pdfPath + PdfFilename;

        foreach (var file in d.GetFiles("*.pdf"))

         { 
            // Rest of the code goes here 
         }

编辑:

通过此代码:

DirectoryInfo d = new DirectoryInfo(@"c:\temp");
foreach (var file in d.GetFiles("*.pdf"))
{
    // Rest of the code goes here 
    Console.WriteLine(file.FullName);
}

我正在获取每个文件的完整路径,例如C:\temp\Power EMC Brochure.pdf. 以后如何在循环中获取每个文件名?我的意思是我需要从完整路径中删除每个文件的名称,例如Power EMC Brochure作为文件名来指定我们的文件管理系统。

是这样的吗?

DirectoryInfo d = new DirectoryInfo(@"c:\temp");
foreach (var file in d.GetFiles("*.pdf"))
{
    // Rest of the code goes here 
    Console.WriteLine(file.FullName);


    file.Name;
}

标签: c#foreach

解决方案


简单到

DirectoryInfo d = new DirectoryInfo(@"c:\temp");
foreach (var file in d.GetFiles("*.pdf"))
{
    // Rest of the code goes here 
    Console.WriteLine(file.FullName);
}

DirectoryInfo.GetFiles返回一组 FileInfo 对象,这些对象的 FullName 是包含路径的完整文件名。因此,您无需再次将源路径与文件名合并以形成执行上传所需的字符串。

如果您需要有关文件的更多详细信息,您只需查看FileInfo 类提供的属性,您还可以在其中找到

foreach (var file in d.GetFiles("*.pdf"))
{
    Console.WriteLine(file.FullName);
    Console.WriteLine(file.Name);  // Without path     
}

推荐阅读