How to encode a URL in WinForms?
Asked Answered
J

3

21

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#?

Juliettejulina answered 21/5, 2011 at 2:45 Comment(0)
L
37

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"
Lagoon answered 21/5, 2011 at 3:9 Comment(1)
You have to mind about length of the string to URL-encode... if it's larger than 32768 you must use HttpUtility.UrlEncode.Tejeda
M
5

Try Uri.EscapeUriString()

Meantime answered 21/5, 2011 at 2:47 Comment(0)
I
5

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.

Immoral answered 15/9, 2017 at 8:55 Comment(1)
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.AppendFormatencoded 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.