1

I am using the WebClient class with cookies as mentioned here: Using CookieContainer with WebClient class

What steps are required to add a custom user agent to every request made by this WebClient?

I tried to put the

Headers.Add(HttpRequestHeader.UserAgent, "...") 

line into

protected override WebRequest GetWebRequest

but that did not work: "This header must be modified using the appropriate property".

Community
  • 1
  • 1
ruliko
  • 11
  • 1
  • 2

2 Answers2

3

from http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx ,

using System;
using System.Net;
using System.IO;

    public class Test
    {
        public static void Main (string[] args)
        {
            if (args == null || args.Length == 0)
            {
                throw new ApplicationException ("Specify the URI of the resource to retrieve.");
            }
            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;)");

            Stream data = client.OpenRead (args[0]);
            StreamReader reader = new StreamReader (data);
            string s = reader.ReadToEnd ();
            Console.WriteLine (s);
            data.Close ();
            reader.Close ();
        }
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
VOX
  • 2,883
  • 2
  • 33
  • 43
0

Kinda late answer but here it goes; I had the same problem as you and solved it by adding a line to the example you linked:

public class CookieAwareWebClient : WebClient
{
    private CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).UserAgent       = "CUSTOM USERAGENT HERE";
            (request as HttpWebRequest).CookieContainer = m_container;
        }
        return request;
    }
}
bennedich
  • 12,150
  • 6
  • 33
  • 41