0
votes

I have code that returns information about the user agent. I want to find the part that says MSIE 10.0 and if it does then write Internet Explorer 10.0 to the log file. Is there a way to do this without regular expressions? I'll use them if necessary, also I don't know if this string will always be same length so I don't think substring would be consistent.

Browser: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.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)

This is the code that returns the string:

var js = driver as IJavaScriptExecutor;
const string script = "return navigator.userAgent"; // get the user agent
if (js != null)
{
    var userAgent = (string) js.ExecuteScript(script);
    Logger.Log(Loglevel.Debug, "Brower: {0}", userAgent);
}
4
User agent parsing is a pain, since the usage is not exactly standard. It looks like there's a library that has already done the work for you: user-agent-string.info - Jon B

4 Answers

2
votes

System.String provides the Contains method that will return true if the particular string that you are searching for is present within the string that is calling Contains.

If you want to avoid hard-coding the version of the browser in your log statement, you can still use Substring with IndexOf to get the value ... the following code would log: "Browser: Internet Explorer 10.0", assuming the value of userAgent is

"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.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)"

        if (userAgent.Contains("MSIE"))
        {
            int index = userAgent.IndexOf("MSIE") + 5; // + length of("MSIE ")
            int length = userAgent.IndexOf(';', index) - index;
            Logger.Log(Loglevel.Debug, "Browser: Internet Explorer {0}",
                userAgent.Substring(index, length)); 
        }    

The first IndexOf will retrieve the index of userAgent past the space after "MSIE". The second IndexOf uses that index as a starting point to find the next semicolon; the length of the difference of those two indices. At that point, the Substring call will return the version number associated with MSIE in the userAgent string.

3
votes

You can simply call Contains to check if specified string contains another string:

if (userAgent.Contains("MSIE 10.0")){
    ...
}
2
votes

You could try using a string.Contains() call on the user agent string.

bool contains = userAgent.Contains("MSIE 10.0");
if(contains)
{
  //whatever
}

Simple, no regex. I use it in some different projects, works ok. But beware false positives if the string you are looking for changes.

2
votes
if(userAgent.Contains("MSIE 10.0"))
      File.AppendAllText("Logfilepath","InternetExplorer 10.0");