I'm creating a Windows application and I need to pass an encoded URL. But I'm not sure how to encode it in WinForms C#?
How to encode a URL in WinForms?
If you need to URL-encode data for a querystring, you can use either Uri.EscapeDataString or, if you don't mind referencing System.Web, HttpUtility.UrlEncode:
var rawString = @"this & that";
var uriEncoded = Uri.EscapeDataString(rawString);
var httpUtilityEncoded = HttpUtility.UrlEncode(rawString);
They're very similar but can produce subtly different results in the way special characters, like spaces, are encoded:
Console.WriteLine(uriEncoded);
// uriEncoded = "this%20%26%20that"
Console.WriteLine(httpUtilityEncoded);
// httpUtilityEncoded = "this+%26+that"
Did you tried with:
var url = System.Net.WebUtility.UrlEncode(string);
You don't need a dependency on System.Web and you can use it in PCL, I used it in my Xamarin forms project.
UPDATE: If you don't have access to HttpUtility class from System.Web that means its replaced with WebUtility. In case if you creating
UriBuilder
class where you append your encoded string with UriBuilder.AppendFormat
encoded value will be in Builder.Uri.AbsoluteUri field. If you say .ToString() on UriBuilder class, not all characters will be encoded. On this, I preferably think on umlauts, which you can find in the German language for example. –
Immoral © 2022 - 2024 — McMap. All rights reserved.
HttpUtility.UrlEncode
. – Tejeda