How to post a page using C#

If you should ever desire to do some webrequesting and posting some values to a webpage and afterwards reading the results. Then you can use the following snippet


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace PageScraper
    class Program
        static void Main(string[] args)
            string postdata = "q=control&field=value";
            byte[] data = Encoding.Default.GetBytes(postdata);
            WebRequest w = WebRequest.Create("");
            w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded";
            w.ContentLength = data.Length;
            Stream s = w.GetRequestStream();
            s.Write(data, 0, data.Length);
            HttpWebResponse resp = w.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(resp.GetResponseStream());
            string res = sr.ReadToEnd();
Comments are closed