在C#中无需对话框与按钮,直接从文件夹加载PDF文件的方法
在C#中自动加载并打开指定文件夹的PDF文件
下面提供两种无需手动触发(无按钮、无文件对话框)的实现方案,可根据需求选择:
方案1:调用系统默认程序自动打开PDF
这种方式简单直接,程序启动后自动调用系统关联的PDF阅读器打开目标文件。
实现代码
在窗体的Load事件中执行加载逻辑(窗体启动时自动触发):
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; namespace AutoPdfLoader { public partial class MainForm : Form { public MainForm() { InitializeComponent(); this.Load += OnFormLoad; } private void OnFormLoad(object sender, EventArgs e) { // 替换为你的PDF文件路径,支持绝对路径或相对路径 string targetPdfPath = @"D:\Documents\Sample.pdf"; if (File.Exists(targetPdfPath)) { try { Process.Start(new ProcessStartInfo(targetPdfPath) { UseShellExecute = true // .NET Core/5+ 需显式设置,确保启动关联程序 }); } catch (Exception ex) { MessageBox.Show($"打开失败:{ex.Message}"); } } else { MessageBox.Show("指定的PDF文件不存在!"); } } } }
扩展:自动加载文件夹内第一个PDF
如果需要自动加载目标文件夹下的第一个PDF文件,可替换路径逻辑为:
string pdfFolder = @"D:\PdfFiles"; var pdfFiles = Directory.GetFiles(pdfFolder, "*.pdf", SearchOption.TopDirectoryOnly); if (pdfFiles.Length > 0) { string firstPdf = pdfFiles[0]; // 执行打开操作(同上述代码) } else { MessageBox.Show("目标文件夹中未找到PDF文件!"); }
方案2:在程序窗口内嵌入显示PDF
如果希望在自己的程序界面内显示PDF,无需调用外部阅读器,可使用第三方库PdfiumViewer实现。
步骤1:安装依赖
通过NuGet包管理器安装PdfiumViewer(若为.NET Core项目,需额外安装对应架构的PdfiumViewer.Native包,如PdfiumViewer.Native.x86_64)。
实现代码
using System; using System.IO; using System.Windows.Forms; using PdfiumViewer; namespace EmbeddedPdfLoader { public partial class MainForm : Form { public MainForm() { InitializeComponent(); this.Load += OnFormLoad; } private void OnFormLoad(object sender, EventArgs e) { string targetPdfPath = @"D:\Documents\Sample.pdf"; if (File.Exists(targetPdfPath)) { try { // 创建PDF查看器控件并填充整个窗口 var pdfViewer = new PdfViewer { Dock = DockStyle.Fill }; this.Controls.Add(pdfViewer); // 加载PDF文件 using (var fileStream = File.OpenRead(targetPdfPath)) { pdfViewer.Load(fileStream); } } catch (Exception ex) { MessageBox.Show($"加载失败:{ex.Message}"); } } else { MessageBox.Show("指定的PDF文件不存在!"); } } } }
内容的提问来源于stack exchange,提问作者Mithun
相关产品推荐
相关产品推荐

