如何解决WPF中的System.UnauthorizedAccessException异常
解决PDF写入桌面时的“路径访问被拒绝”异常
核心问题分析
你代码里的document.Save方法传入的是文件夹路径,而非具体的PDF文件名。PdfDocument.Save要求传入完整的文件路径(包含文件名和.pdf后缀),直接传文件夹会导致程序试图将文件内容写入文件夹本身,从而触发权限异常。
修复步骤
修改保存路径为完整文件名
将保存路径改为包含具体文件名的格式,示例如下:// 生成带订单ID的唯一文件名 string filePath = $@"C:\Users\HP\Desktop\CourseWorkPDFs\Чек №{_orderId}.pdf"; document.Save(filePath);确保目标文件夹存在
如果CourseWorkPDFs文件夹尚未创建,需先添加文件夹创建逻辑,避免因文件夹不存在引发错误:string folderPath = @"C:\Users\HP\Desktop\CourseWorkPDFs"; // 文件夹不存在则创建 if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } // 拼接完整文件路径 string filePath = Path.Combine(folderPath, $"Чек №{_orderId}.pdf"); document.Save(filePath);注意:需要引用
System.IO命名空间才能使用Directory和Path类。检查文件夹权限(可选)
若上述操作后仍报错,可手动确认桌面文件夹权限:- 右键
CourseWorkPDFs文件夹(或桌面)→ 属性 → 安全选项卡 - 确保当前用户拥有写入权限,无权限则手动添加。
- 右键
修复后的完整代码示例
using System.IO; using PdfSharp.Drawing; using PdfSharp.Pdf; using System.Text; public void GeneratePDF() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); PdfDocument document = new PdfDocument(); document.Info.Title = $"Чек №{_orderId}"; PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Arial", 18); gfx.DrawString($"{document.Info.Title}", new XFont("Arial", 40, XFontStyle.Bold), XBrushes.Black, new XPoint(200, 70)); // 处理文件夹与文件路径 string folderPath = @"C:\Users\HP\Desktop\CourseWorkPDFs"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } string filePath = Path.Combine(folderPath, $"Чек №{_orderId}.pdf"); document.Save(filePath); }
内容的提问来源于stack exchange,提问作者TeraBasedProgrammer
相关产品推荐
相关产品推荐

