0

I'm familiar with Winform and WPF, but new to web developing. One day saw WebClient.UploadValues and decided to try it.

static void Main(string[] args)
{
    using (var client = new WebClient())
    {
        var values = new NameValueCollection();
        values["thing1"] = "hello";
        values["thing2"] = "world";
        //A single file that contains plain html
        var response = client.UploadValues("D:\\page.html", values);
        var responseString = Encoding.Default.GetString(response);
        Console.WriteLine(responseString);
    }
    Console.ReadLine();
}

After run, nothing printed, and the html file content becomes like this:

thing1=hello&thing2=world

Could anyone explain it, thanks!

Community
  • 1
  • 1
Lei Yang
  • 3,970
  • 6
  • 38
  • 59
  • Maybe worth looking at the new and shiny thing from the rest world called httpclient, it mimics http in a more natural way - just my 2 cents . – loneshark99 Dec 25 '15 at 08:38

2 Answers2

2

The UploadValues method is intended to be used with the HTTP protocol. This means that you need to host your html on a web server and make the request like that:

var response = client.UploadValues("http://some_server/page.html", values);

In this case the method will send the values to the server by using application/x-www-form-urlencoded encoding and it will return the response from the HTTP request.

I have never used the UploadValues with a local file and the documentation doesn't seem to mention anything about it. They only mention HTTP or FTP protocols. So I suppose that this is some side effect when using it with a local file -> it simply overwrites the contents of this file with the payload that is being sent.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

You are using WebClient not as it was intended.

The purpose of WebClient.UploadValues is to upload the specified name/value collection to the resource identified by the specified URI.

But it should not be some local file on your disk, but instead it should be some web-service listening for requests and issuing responces.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71