虛擬路徑的檔案保存錯誤
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這樣受保護的資料夾時,以足夠的權限運行。 - 確認路徑:在開發過程中記錄解析的實體路徑以確認其指向您期望的位置。
警告避免在生產中硬編碼磁碟機代號; 在運行時解析路徑,以便應用程式能跨環境運行。
準備開始了嗎?
Nuget 下載 20,296,129 | 版本: 2026.7 剛剛發布

