views:

598

answers:

2

When I've uploaded content from my C# app to a website in the past, I've used a POST request like so:

    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + this.server + "/log.php");
    wr.Method = "POST";
    wr.ContentType = "application/x-www-form-urlencoded";
    string paramString = "v=" + this.version + "&m=" + this.message;
    wr.ContentLength = paramString.Length;
    StreamWriter stOut = new StreamWriter(wr.GetRequestStream(), System.Text.Encoding.ASCII);
    stOut.Write(paramString);
    stOut.Close();

My problem is that now I'm in a situation where this.message will very likely contain newlines, tabs, and special characters including "&" and "=". Do I need to escape this content. If so, how?

+5  A: 

You can use HttpUtility.HtmlEncode/HtmlDecode or UrlEncode/UrlDecode as appropriate.

Paul Alexander
Yup. UrlEncode was what I needed:http://msdn.microsoft.com/en-us/library/4fkewx0t.aspxThanks.
Andrew
Crud. This won't work. I need a .Net 2.0 method.
Andrew
That's been in since 1.0 :)
Jon Skeet
(If you're not finding it with Intellisense, make sure you're referencing the System.Web assembly.)
Jon Skeet
yeah... just saw that. Sorry. I saw the .Net 3.5 on the doc page and got scared. Jumped the gun a little.
Andrew
+1  A: 

Just for reference, the solution to my problem was in:

System.Web.HttpUtility.UrlEncode

Which is supported by all versions of the .Net framework =p

Specifically, I'm using the overload that takes a string as an argument. Running this on all parameter values will make them safe for POSTing.

Andrew