.NETヘルプ C# URL Encode(開発者向けの動作方法) Curtis Chau 更新日:7月 28, 2025 Download IronPDF NuGet Download テキストの検索と置換 テキストと画像のスタンプ Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article URL encoding and decoding are techniques used in C# to ensure the safe transmission of data within URLs. In C#, these operations are commonly encountered when dealing with web applications, API calls, or any scenario where data needs to be passed through the internet securely and reliably. In this article, we'll explore the URL encoding method and the IronPDF library. URL Encoding in C# When you encode a URL, you change its characters into a form that can be safely sent across the internet, avoiding any misunderstandings. This is because URLs can only be sent over the Internet using the ASCII character set. Characters that aren't part of this set, or have special meanings in URLs (like spaces, ampersands, and equals signs), need to be represented using percent-encoding (e.g., spaces become %20). C# provides built-in methods to accomplish this task. URL Decoding in C# URL decoding transforms encoded characters back to their original state upon arrival at their destination. This is essential for the receiving application to correctly understand and process the data as intended. Decoding turns the percent-encoded characters back into their original symbols, making the data readable and usable again. Encoding Methods in C# In C#, there are multiple ways to perform URL encoding, each suited for different scenarios. These methods are primarily found within the System.Web and System.Net namespaces, offering developers flexibility in how they encode URLs. Here's a brief overview of the methods available: HttpUtility.UrlEncode Method (System.Web): This is perhaps the most commonly used method for URL encoding in a web application. It converts characters into a percent-encoded format, making the string safe for transmission over the URL. It's especially useful in ASP.NET projects for encoding query strings and form parameters. HttpUtility.UrlPathEncode Method (System.Web): Unlike UrlEncode, UrlPathEncode is designed specifically for encoding the path portion of a URL, leaving the query string untouched. It's important to note that this method does not encode the entire URL but rather the path part, ensuring that the hierarchical structure of the URL is preserved. Uri.EscapeUriString Method (System): This method is intended for escaping URI strings, turning all characters that are not allowed in a URI into their percent-encoded equivalents. However, it does not encode certain characters, such as the slash (/) and question mark (?), because they are considered valid URI characters. Uri.EscapeDataString Method (System): This method is designed for encoding a string to be used in a query part of a URI. It encodes all characters except for the unreserved characters defined in RFC 3986. It's more aggressive than EscapeUriString, ensuring that the data is safely encoded for transmission within URLs. Let's understand the first three encoding methods as described above, and their working by understanding their code examples. Code Example of HttpUtility.UrlEncode Method using System; using System.Web; class Program { static void Main() { string originalPath = "/api/search/Hello World!"; string encodedPath = UrlEncode(originalPath); Console.WriteLine("Original Path: " + originalPath); Console.WriteLine("Encoded Path: " + encodedPath); } public static string UrlEncode(string originalString) { return HttpUtility.UrlEncode(originalString); } } using System; using System.Web; class Program { static void Main() { string originalPath = "/api/search/Hello World!"; string encodedPath = UrlEncode(originalPath); Console.WriteLine("Original Path: " + originalPath); Console.WriteLine("Encoded Path: " + encodedPath); } public static string UrlEncode(string originalString) { return HttpUtility.UrlEncode(originalString); } } Imports System Imports System.Web Friend Class Program Shared Sub Main() Dim originalPath As String = "/api/search/Hello World!" Dim encodedPath As String = UrlEncode(originalPath) Console.WriteLine("Original Path: " & originalPath) Console.WriteLine("Encoded Path: " & encodedPath) End Sub Public Shared Function UrlEncode(ByVal originalString As String) As String Return HttpUtility.UrlEncode(originalString) End Function End Class $vbLabelText $csharpLabel Namespace Inclusion: The System.Web namespace is included at the beginning of the code. Original String: We define a string variable originalString containing the characters to encode for safe transmission in a URL. This includes spaces and punctuation marks that could potentially cause issues if included in a URL without encoding. Encoding: The HttpUtility.UrlEncode method is called with originalString as its argument. This method processes the string and returns a new string where unsafe characters are replaced with their percent-encoded equivalents. For example, spaces are replaced with %20. Output: Finally, the program prints both the original and encoded strings to the console. Code Example of HttpUtility.UrlPathEncode Method using System; using System.Web; class Program { static void Main() { // Define the original URL path, which includes spaces. string originalPath = "/api/search/Hello World!"; // Use the HttpUtility.UrlPathEncode method to encode the path. string encodedPath = HttpUtility.UrlPathEncode(originalPath); // Output the original and encoded paths to the console. Console.WriteLine("Original Path: " + originalPath); Console.WriteLine("Encoded Path: " + encodedPath); } } using System; using System.Web; class Program { static void Main() { // Define the original URL path, which includes spaces. string originalPath = "/api/search/Hello World!"; // Use the HttpUtility.UrlPathEncode method to encode the path. string encodedPath = HttpUtility.UrlPathEncode(originalPath); // Output the original and encoded paths to the console. Console.WriteLine("Original Path: " + originalPath); Console.WriteLine("Encoded Path: " + encodedPath); } } Imports System Imports System.Web Friend Class Program Shared Sub Main() ' Define the original URL path, which includes spaces. Dim originalPath As String = "/api/search/Hello World!" ' Use the HttpUtility.UrlPathEncode method to encode the path. Dim encodedPath As String = HttpUtility.UrlPathEncode(originalPath) ' Output the original and encoded paths to the console. Console.WriteLine("Original Path: " & originalPath) Console.WriteLine("Encoded Path: " & encodedPath) End Sub End Class $vbLabelText $csharpLabel Character Entity Equivalents in URL Encoding: The process shown transforms the string value of a URL path, converting spaces into their character entity equivalents (%20) for web compatibility. This is crucial because URLs cannot contain actual space characters. String Value and URL String Handling: The originalPath variable's string value is "/api/search/Hello World!", which is a typical example of a URL string needing encoding due to the inclusion of spaces. Although this example uses a specific version of HttpUtility.UrlPathEncode without method overloads, it's important to note the method's design intention for encoding URL paths. Developers should be aware of method overloads when they exist, as they provide alternative ways to use a method, often by accepting different types of input or providing additional functionality. Encoding Object and String URL Transformation: The encoding object in this context is implicit in the HttpUtility.UrlPathEncode method's operation, which takes a string URL and returns its encoded form. This method ensures that the structure of the URL path remains intact while encoding special characters to their appropriate representations. Encoded Path Output: The program demonstrates the transformation from the original path to the encoded path. This is a direct example of encoding a string URL to adapt it for web transmission, addressing the potential issues spaces and other special characters might introduce. Code Example of Uri.EscapeUriString Method using System; class Program { static void Main() { string originalUri = "https://example.com/search?query=Hello World!"; string escapedUri = Uri.EscapeUriString(originalUri); Console.WriteLine("Original URI: " + originalUri); Console.WriteLine("Escaped URI: " + escapedUri); } } using System; class Program { static void Main() { string originalUri = "https://example.com/search?query=Hello World!"; string escapedUri = Uri.EscapeUriString(originalUri); Console.WriteLine("Original URI: " + originalUri); Console.WriteLine("Escaped URI: " + escapedUri); } } Imports System Friend Class Program Shared Sub Main() Dim originalUri As String = "https://example.com/search?query=Hello World!" Dim escapedUri As String = Uri.EscapeUriString(originalUri) Console.WriteLine("Original URI: " & originalUri) Console.WriteLine("Escaped URI: " & escapedUri) End Sub End Class $vbLabelText $csharpLabel Original URI: The originalUri variable is initialized with a string representing a full URI, including a query string with spaces and special characters. To ensure the URI is correctly processed by web browsers and servers, these special characters need to be 'escaped'. Escaping the URI: The Uri.EscapeUriString method is invoked with originalUri as its argument. This method scans the URI string and escapes characters that are not allowed or could cause ambiguity in a URI. Output: The program prints both the original and the escaped URI to the console. IronPDF: C# PDF Library IronPDF is a PDF library that simplifies creating, editing, and manipulating PDF files within .NET applications. Designed to seamlessly integrate with C# and VB.NET, IronPDF offers developers the functions to generate PDFs from HTML or directly from text. Whether you need to automate invoice generation, create dynamic reports, or manage documents in a .NET environment, IronPDF stands out for its ease of use and comprehensive set of features. The highlight of IronPDF is its HTML to PDF Conversion feature, maintaining your layouts and styles. This allows for PDF creation from web content, perfect for reports, invoices, and documentation. HTML files, URLs, and HTML strings can be converted to PDFs easily. using IronPdf; class Program { static void Main(string[] args) { var renderer = new ChromePdfRenderer(); // 1. Convert HTML String to PDF var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"; var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent); pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf"); // 2. Convert HTML File to PDF var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath); pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf"); // 3. Convert URL to PDF var url = "http://ironpdf.com"; // Specify the URL var pdfFromUrl = renderer.RenderUrlAsPdf(url); pdfFromUrl.SaveAs("URLToPDF.pdf"); } } using IronPdf; class Program { static void Main(string[] args) { var renderer = new ChromePdfRenderer(); // 1. Convert HTML String to PDF var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"; var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent); pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf"); // 2. Convert HTML File to PDF var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath); pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf"); // 3. Convert URL to PDF var url = "http://ironpdf.com"; // Specify the URL var pdfFromUrl = renderer.RenderUrlAsPdf(url); pdfFromUrl.SaveAs("URLToPDF.pdf"); } } Imports IronPdf Friend Class Program Shared Sub Main(ByVal args() As String) Dim renderer = New ChromePdfRenderer() ' 1. Convert HTML String to PDF Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>" Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent) pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf") ' 2. Convert HTML File to PDF Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath) pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf") ' 3. Convert URL to PDF Dim url = "http://ironpdf.com" ' Specify the URL Dim pdfFromUrl = renderer.RenderUrlAsPdf(url) pdfFromUrl.SaveAs("URLToPDF.pdf") End Sub End Class $vbLabelText $csharpLabel Working Code Example with URL Encoding In the following example, we'll see how to use IronPDF in conjunction with URL encoding to generate a PDF from a web page. The scenario involves encoding a URL to ensure it's correctly formatted for web requests, then using IronPDF to convert the content at that URL into a PDF document. Install IronPDF Library First, ensure you have IronPDF installed in your project. If you're using NuGet Package Manager, you can install it by running: Install-Package IronPdf Code Example Now, let's dive into the code: using System.Web; using IronPdf; class Program { static void Main(string[] args) { License.LicenseKey = "License-Key"; // Set your IronPDF license key string baseUrl = "https://example.com/search"; // The query parameter with spaces that needs to be encoded string query = "Hello World!"; // Encoding the query parameter to ensure the URL is correctly formatted string encodedQuery = HttpUtility.UrlEncode(query); // Constructing the full URL with the encoded query parameter string fullUrl = $"{baseUrl}?query={encodedQuery}"; // Initialize the IronPDF HtmlToPdf renderer var renderer = new ChromePdfRenderer(); // Convert the web page at the encoded URL to a PDF document var pdf = renderer.RenderUrlAsPdf(fullUrl); // Save the PDF to a file string filePath = "webpage.pdf"; pdf.SaveAs(filePath); Console.WriteLine($"PDF successfully created from: {fullUrl}"); Console.WriteLine($"Saved to: {filePath}"); } } using System.Web; using IronPdf; class Program { static void Main(string[] args) { License.LicenseKey = "License-Key"; // Set your IronPDF license key string baseUrl = "https://example.com/search"; // The query parameter with spaces that needs to be encoded string query = "Hello World!"; // Encoding the query parameter to ensure the URL is correctly formatted string encodedQuery = HttpUtility.UrlEncode(query); // Constructing the full URL with the encoded query parameter string fullUrl = $"{baseUrl}?query={encodedQuery}"; // Initialize the IronPDF HtmlToPdf renderer var renderer = new ChromePdfRenderer(); // Convert the web page at the encoded URL to a PDF document var pdf = renderer.RenderUrlAsPdf(fullUrl); // Save the PDF to a file string filePath = "webpage.pdf"; pdf.SaveAs(filePath); Console.WriteLine($"PDF successfully created from: {fullUrl}"); Console.WriteLine($"Saved to: {filePath}"); } } Imports System.Web Imports IronPdf Friend Class Program Shared Sub Main(ByVal args() As String) License.LicenseKey = "License-Key" ' Set your IronPDF license key Dim baseUrl As String = "https://example.com/search" ' The query parameter with spaces that needs to be encoded Dim query As String = "Hello World!" ' Encoding the query parameter to ensure the URL is correctly formatted Dim encodedQuery As String = HttpUtility.UrlEncode(query) ' Constructing the full URL with the encoded query parameter Dim fullUrl As String = $"{baseUrl}?query={encodedQuery}" ' Initialize the IronPDF HtmlToPdf renderer Dim renderer = New ChromePdfRenderer() ' Convert the web page at the encoded URL to a PDF document Dim pdf = renderer.RenderUrlAsPdf(fullUrl) ' Save the PDF to a file Dim filePath As String = "webpage.pdf" pdf.SaveAs(filePath) Console.WriteLine($"PDF successfully created from: {fullUrl}") Console.WriteLine($"Saved to: {filePath}") End Sub End Class $vbLabelText $csharpLabel Explanation of the Code The example starts with a base URL and a query string containing spaces. The query string is encoded using HttpUtility.UrlEncode to ensure it's safely transmitted in the URL. After encoding the query, it's appended to the base URL to form the complete URL that will be accessed. With the full, encoded URL ready, IronPDF's ChromePdfRenderer is used to fetch the web page at that URL and convert it into a PDF document. This involves creating an instance of the ChromePdfRenderer class and then calling RenderUrlAsPdf with the encoded URL. Finally, the generated PDF is saved to a file using the SaveAs method. The resulting file is a PDF document of the web page content, accessible via the encoded URL. Here is the output PDF file: 結論 To wrap up, C# provides powerful capabilities for URL encoding and decoding, ensuring data can be securely and efficiently transmitted over the internet. Through the built-in methods within the System.Web and System.Net namespaces, developers can encode URLs to prevent issues with special characters and decode them to their original form for accurate data interpretation. For those interested in exploring the IronPDF Trial License Offerings, they provide an opportunity to evaluate its functionality firsthand. Should you decide to integrate IronPDF into your projects, licenses start at $799, offering a comprehensive suite of features to meet your PDF manipulation needs within the .NET framework. よくある質問 C#でURLをエンコードするにはどうすればいいですか? C#では、HttpUtility.UrlEncodeやUri.EscapeDataStringのようなメソッドを使用してURLをエンコードできます。これらのメソッドは、文字をパーセントエンコード形式に変換し、インターネット上での安全な送信を確保します。 URLエンコードとデコードの違いは何ですか? URLエンコードは、特別な文字をパーセントエンコード形式に変換して、安全なデータ伝送をURLで確保します。一方、デコードはこれらのエンコードされた文字を元の形式に変換して、正確なデータ解釈を行います。 C#でURLからPDFを作成するにはどうすればいいですか? C#でIronPDFを使用してURLをPDFに変換することができます。IronPDFは、ウェブページの内容を直接キャプチャしてPDFドキュメントに変換し、正確なウェブリクエストのためのURLエンコード技術を統合します。 ウェブアプリケーションでURLエンコードが重要なのはなぜですか? URLエンコードは、ウェブアプリケーションでデータがURLに含まれて安全かつエラーなく送信されるようにするために重要です。安全でない文字をパーセントエンコード形式に置き換えることで、潜在的なデータ破損やセキュリティ問題を防ぎます。 C#でのPDF生成をどのようにURLエンコードで強化できますか? PDFを生成する前にURLエンコードを適用することで、ドキュメントに含まれるURLが正しく形式化され安全に送信されるようにすることができます。IronPDFのようなライブラリは、その後、ウェブコンテンツをPDFに変換するときにこれらのURLを正確に処理できます。 C#でのURLデコードのための方法は何ですか? C#はHttpUtility.UrlDecodeやUri.UnescapeDataStringのような方法を提供しています。これらのメソッドはエンコードプロセスを逆にし、パーセントエンコードされた文字を元の形式に戻します。 URLエンコードはAPI呼び出しをどのように助けますか? URLエンコードは、クエリパラメータ内の特別な文字が安全に送信されることを確保し、API呼び出し中のエラーを防ぎます。これはウェブアプリケーションでクライアントとサーバー間でデータを確実に渡すために不可欠です。 IronPDFは、PDFを生成するときにURLエンコードを自動的に処理できますか? はい、IronPDFはウェブページをPDFに変換するときにURLエンコードを自動で処理できます。PDF生成プロセス中にURLが正しく形式化され、処理されることを保証し、ウェブコンテンツとのシームレスな統合を提供します。 Curtis Chau 今すぐエンジニアリングチームとチャット テクニカルライター Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。 関連する記事 更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む 更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む 更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む C# Unit Testing(開発者向けの動作方法)IndexOf C#(開発者向けの動...
更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む
更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む
更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む