Setting the User-Agent header for a WebClient request

AndreiC picture AndreiC · Aug 7, 2012 · Viewed 124.6k times · Source

What is the proper way of setting the User-Agent header for a WebClient request for Windows Phone 7? I found 2 options, but not sure which one is the correct one. Considering a WebClient object:

WebClient client = new WebClient();

I saw 2 options:

  1. set the User-Agent using:

    client.Headers["User-Agent"] = "myUserAgentString";
    
  2. set the User-Agent using the WebHeaderCollection:

    WebHeaderCollection headers = new WebHeaderCollection();
    headers[HttpRequestHeader.UserAgent] = "userAgentString";
    client.Headers = headers;
    

Can you please advise which of the 2 methods above is the proper one?

Answer

Doc Roms picture Doc Roms · Aug 7, 2012

You can check the WebClient documentation for a C# sample that adds a User-Agent to your WebClient and here for a sample for Windows Phone.

This is the sample for C#:

WebClient client = new WebClient ();

// Add a user agent header in case the 
// requested URI contains a query.

client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; " + 
                                  "Windows NT 5.2; .NET CLR 1.0.3705;)");

This is a sample for Windows Phone (Silverlight):

request.Headers["UserAgent"] = "appname";
// OR
request.UserAgent = "appname";