c# - 循环遍历目录中的每个 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;
}
解决方案
简单到
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
}
推荐阅读
- typescript - RxJs forkJoin:当所有可观察对象都出错或成功时执行
- apache-spark - 在 GCP Dataproc 上配置 Spark 执行器
- gdb - 收到我不明白的劣质流程消息
- mongodb - mongoDB spring数据中的等效替换方法SQL
- django - 阅读 Django 上的选择选项
- python-sphinx - 构建错误“必须只有一个参数:DEST_DIR”
- java - 使用注解配置引用多个 bean
- laravel - 两个表中的一个数据
- reactjs - 如何在反应5秒后自动关闭甜蜜警报
- c# - 带有 c# 和 f# 项目的根文件夹中的 Directory.Build.props 会导致问题