Lei Yang
Lei Yang

Reputation: 4335

Why does WebClient.UploadValues overwrites my html web page?

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!

Upvotes: 0

Views: 291

Answers (2)

Andrey Korneyev
Andrey Korneyev

Reputation: 26856

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.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

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.

Upvotes: 2

Related Questions