19

I need to parse UserAgent strings from a console app and this seems like a simple way to do it, but I obviously don't have an HttpRequest object and can't seem to make a fake one with a User-Agent header (I get platform not supported exception). Is there any way to do this, or should I start exploring other alternatives to user agent parsing?

Nathan Baulch
  • 20,233
  • 5
  • 52
  • 56
Jody Powlette
  • 1,573
  • 2
  • 17
  • 21
  • what kind of page request you want to capture???? specially from console app? – Shoaib Shaikh Oct 08 '10 at 15:01
  • No page request. I have a list of user agents in a text file and I want to parse out Browser, Version, OS and a couple other things - all of which would have been available through Request.Browser, but now I'm trying to get them from a console app and list of UserAgent strings. – Jody Powlette Oct 08 '10 at 15:14

1 Answers1

27

The User-Agent header can be parsed by the HttpBrowserCapabilities class with the help of a BrowserCapabilitiesFactory, as follows:

var userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.10) " +
                "Gecko/20100914 Firefox/3.6.10";
var browser = new HttpBrowserCapabilities {
    Capabilities = new Hashtable {{string.Empty, userAgent}}
};
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), browser);
Nathan Baulch
  • 20,233
  • 5
  • 52
  • 56
  • I want to run this outside of an asp.net environment (analyzing log files). It doesn't seem to be determining the agent type and version very well. "Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/37.0.2062.120+Safari/537.36" = Chrome 37, but "Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+6.1;+Trident/4.0;+SLCC2;+.NET+CLR+2.0.50727;+.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729;+Media+Center+PC+6.0;+.NET4.0C;+.NET4.0E;+InfoPath.3;+SynapseWorkstation.3.2.1;+MS-RTC+LM+8;+Tablet+PC+2.0)" = Mozilla. – Jeremy May 20 '15 at 21:57