c# sending data to php url

user2847609 picture user2847609 · Oct 4, 2013 · Viewed 20.1k times · Source

okay so I have a c# console source code I have created but it does not work how I want it to.

I need to post data to a URL the same as if I was going to input it an a browser.

url with data = localhost/test.php?DGURL=DGURL&DGUSER=DGUSER&DGPASS=DGPASS

Here is my c# script that does not do it the way I want to I want it to post the data as if I had typed it like above.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections.Specialized;
using System.Net;
using System.IO;


namespace ConsoleApplication1
{
  class Program
  {
     static void Main(string[] args)
     {
        string URL = "http://localhost/test.php";
        WebClient webClient = new WebClient();

        NameValueCollection formData = new NameValueCollection();
        formData["DGURL"] = "DGURL";
        formData["DGUSER"] = "DGUSER";
        formData["DGPASS"] = "DGPASS";

        byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
        string responsefromserver = Encoding.UTF8.GetString(responseBytes);
        Console.WriteLine(responsefromserver);
        webClient.Dispose();
    }
  }
}

I have also triead another method in c# this does now work either

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections.Specialized;
using System.Net;
using System.IO;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string URI = "http://localhost/test.php";
            string myParameters = "DGURL=value1&DGUSER=value2&DGPASS=value3";

            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "text/html";
                string HtmlResult = wc.UploadString(URI, myParameters);
                System.Threading.Thread.Sleep(500000000);
            }
        }
    }
}

I have been trying to figure a way to do this in my c# console for days now

Answer

Karl-Johan Sjögren picture Karl-Johan Sjögren · Oct 5, 2013

Since what you seem to want is a GET-request with querystrings and not a POST you should do it like this instead.

static void Main(string[] args)
{
    var dgurl = "DGURL", user="DGUSER", pass="DGPASS";
    var url = string.Format("http://localhost/test.php?DGURL={0}&DGUSER={1}&DGPASS=DGPASS", dgurl, user, pass);
    using(var webClient = new WebClient()) 
    {
        var response = webClient.DownloadString(url);
        Console.WriteLine(response);
    }
}

I also wrapped your WebClient in a using-statement so you don't have to worry about disposing it yourself even if it would throw an exception when downloading the string.

Another thing to think about is that you might want to url-encode the parameters in the querystring using WebUtility.UrlEncode to be sure that it doesn't contain invalid chars.