0

Any C# method to convert into HTML character entity strings?

Basically, I need to encode a URL. Using HttpUtility.UrlEncode() I get to

http://server/sites/blank/_vti_bin/UploadService/UploadService.svc/Upload/http%3a%2f%2fserver%2fsites%2fblank%2fdoclib1%2ffile.pdf

Problem is, that causes a "400 Bad Request" for my service.

Fix is to replace %3A with : and so on, makes sense?

svick
  • 236,525
  • 50
  • 385
  • 514
Ariel
  • 5,752
  • 5
  • 49
  • 59
  • 1
    No, this doesn't make sense. URLs really should use URL encoding, not HTML encoding. If the service you're using requires that, I would suggest that you ask the authors of the service to fix it. – svick Jan 26 '13 at 15:25
  • possible duplicate of [HtmlEncode from Class Library](http://stackoverflow.com/questions/1144535/c-sharp-htmlencode-from-class-library) – svick Jan 26 '13 at 15:28
  • looks like 400 bad req is for some other reason, r u sure its due to url formatting? – Parimal Raj Jan 26 '13 at 15:31
  • @svick - Agree with your first comment. But HtmlEncode does not convert `:` or `/` like OP requested so it's not a duplicate... – Blachshma Jan 26 '13 at 15:52
  • @AppDeveloper, sure, it's because characters like : or / are not encoded, verified. – Ariel Jan 26 '13 at 16:29
  • @Ariel What about Uri.EscapeDataString? – omittones Jan 27 '13 at 14:20

2 Answers2

1

I believe the best method to encode URLs for transfer over another URL is by using Uri.EscapeDataString(). The problem might be lowercase letters (%3a instead of %3A) in your encoded string.

var escdata = Uri.EscapeDataString(@"http://server/sites/blank/doclib1/file.pdf?test=a+b c");
//  http%3A%2F%2Fserver%2Fsites%2Fblank%2Fdoclib1%2Ffile.pdf%3Ftest%3Da%2Bb%20c

var escuris = Uri.EscapeUriString(@"http://server/sites/blank/doclib1/file.pdf?test=a+b c");
//  http://server/sites/blank/doclib1/file.pdf?test=a+b%20c

var urlencd = HttpUtility.UrlEncode(@"http://server/sites/blank/doclib1/file.pdf?test=a+b c");
//  http%3a%2f%2fserver%2fsites%2fblank%2fdoclib1%2ffile.pdf%3ftest%3da%2bb+c

var urlpenc = HttpUtility.UrlPathEncode(@"http://server/sites/blank/doclib1/file.pdf?test=a+b c");
//  http://server/sites/blank/doclib1/file.pdf?test=a+b c
omittones
  • 847
  • 1
  • 10
  • 23
0

I'm not aware of a built-in function that will do this, but here is a quick-and-dirty solution:

 string s = "http://myurl.com/whatever";

 StringBuilder sb = new StringBuilder();
 foreach (char c in s)
 {
     sb.Append(String.Format("&#x{0:X2};", (uint)c));
 }

 var result = sb.ToString();

And as a one-liner using LINQ:

string s = "http://myurl.com/whatever";
string result = String.Join("", s.SelectMany(c=> String.Format("&#x{0:X2};", (uint)c)).ToArray());
Blachshma
  • 17,097
  • 4
  • 58
  • 72