仮想パスによるファイル保存エラー

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 では Server.MapPath()、それ以外では 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は、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

準備はできましたか?
Nuget ダウンロード 20,296,129 | バージョン: 2026.7 リリースされたばかり
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか? PM > Install-Package IronPdf
サンプルを実行するHTML が PDF に変換されるのを確認します。