虛擬路徑的檔案保存錯誤

This article was translated from English: Does it need improvement?
Translated
View the article in English

在ASP.NET應用程式中,PdfDocument.SaveAs() 可能會出現如下錯誤:

IronPDF could not write to the file '~/PDFFiles/mydocument.pdf'. It may be open in a PDF viewer.

訊息指向一個被鎖定的檔案,但真正的原因通常是路徑問題。 IronPDF寫入磁碟需要一個完整的實體路徑,而像 ~/PDFFiles/file.pdf 這樣的值是ASP.NET的虛擬路徑,檔案系統無法解析。

將虛擬路徑映射到實體路徑

在保存之前轉換虛擬路徑,在ASP.NET Web Forms中使用HostingEnvironment.MapPath()

string virtualPath = "~/PDFFiles/mydocument.pdf";
string physicalPath = Server.MapPath(virtualPath); // or HostingEnvironment.MapPath outside Web Forms
pdf.SaveAs(physicalPath);
string virtualPath = "~/PDFFiles/mydocument.pdf";
string physicalPath = Server.MapPath(virtualPath); // or HostingEnvironment.MapPath outside Web Forms
pdf.SaveAs(physicalPath);
Imports System.Web

Dim virtualPath As String = "~/PDFFiles/mydocument.pdf"
Dim physicalPath As String = Server.MapPath(virtualPath) ' or HostingEnvironment.MapPath outside Web Forms
pdf.SaveAs(physicalPath)
$vbLabelText   $csharpLabel

一個基本的工作範例:

var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://example.com");
string physicalPath = Server.MapPath("~/App_Data/PDFFiles/output.pdf");
pdf.SaveAs(physicalPath);
var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf("https://example.com");
string physicalPath = Server.MapPath("~/App_Data/PDFFiles/output.pdf");
pdf.SaveAs(physicalPath);
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://example.com")
Dim physicalPath As String = Server.MapPath("~/App_Data/PDFFiles/output.pdf")
pdf.SaveAs(physicalPath)
$vbLabelText   $csharpLabel

在您保存之前

  • 目錄是否存在:建立目標資料夾並確認應用程式有寫入權限。
  • 檔案未打開:確保輸出尚未在例如Adobe Reader等檢視器中打開。
  • 受限位置:在寫入像Program Files這樣受保護的資料夾時,以足夠的權限運行。
  • 確認路徑:在開發過程中記錄解析的實體路徑以確認其指向您期望的位置。

警告避免在生產中硬編碼磁碟機代號; 在運行時解析路徑,以便應用程式能跨環境運行。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 20,296,129 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想快速獲得證明嗎? PM > Install-Package IronPdf
執行範例 看您的HTML變成PDF。