how do I detect user operating system
Asked Answered
G

12

31

I have the following code to obtain user details:

HttpBrowserCapabilities bc = HttpContext.Current.Request.Browser;
string UserAgent = HttpContext.Current.Request.UserAgent;

ENT_TrackingData ret = new ENT_TrackingData()
{
    IPAddress = HttpContext.Current.Request.UserHostAddress,
    Browser = bc.Browser + " " + bc.Version,                
    DateStamp = DateTime.Now,
    PageViewed = HttpContext.Current.Request.Url.AbsolutePath,
    NodeId = UmbracoHelper.GetCurrentNodeID(),
    IsMobileDevice = IsMobileDevice(UserAgent),
    Platform = bc.Platform
};

This works great but I noticed that the Platform always says windows NT for my machine not Windows 7. Is there any way to detect this type of information in ASP.Net?

Garamond answered 16/3, 2012 at 9:25 Comment(2)
If you are using Windows 7, your platform is "Windows NT". Maybe you need to look for something that can give you the version number of the platform?Atheling
Read my answer below for the most updated solution.Petrolatum
S
45

Here's what I came up with and it seems to work fairly well:

public String GetUserEnvironment(HttpRequest request)
{
    var browser = request.Browser;
    var platform = GetUserPlatform(request);
    return string.Format("{0} {1} / {2}", browser.Browser, browser.Version, platform);
}

public String GetUserPlatform(HttpRequest request)
{
    var ua = request.UserAgent;

    if (ua.Contains("Android"))
        return string.Format("Android {0}", GetMobileVersion(ua, "Android"));

    if (ua.Contains("iPad"))
        return string.Format("iPad OS {0}", GetMobileVersion(ua, "OS"));

    if (ua.Contains("iPhone"))
        return string.Format("iPhone OS {0}", GetMobileVersion(ua, "OS"));

    if (ua.Contains("Linux") && ua.Contains("KFAPWI"))
        return "Kindle Fire";

    if (ua.Contains("RIM Tablet") || (ua.Contains("BB") && ua.Contains("Mobile")))
        return "Black Berry";

    if (ua.Contains("Windows Phone"))
        return string.Format("Windows Phone {0}", GetMobileVersion(ua, "Windows Phone"));

    if (ua.Contains("Mac OS"))
        return "Mac OS";

    if (ua.Contains("Windows NT 5.1") || ua.Contains("Windows NT 5.2"))
        return "Windows XP";

    if (ua.Contains("Windows NT 6.0"))
        return "Windows Vista";

    if (ua.Contains("Windows NT 6.1"))
        return "Windows 7";

    if (ua.Contains("Windows NT 6.2"))
        return "Windows 8";

    if (ua.Contains("Windows NT 6.3"))
        return "Windows 8.1";

    if (ua.Contains("Windows NT 10"))
        return "Windows 10";

    //fallback to basic platform:
    return request.Browser.Platform + (ua.Contains("Mobile") ? " Mobile " : "");
}

public String GetMobileVersion(string userAgent, string device)
{
    var temp = userAgent.Substring(userAgent.IndexOf(device) + device.Length).TrimStart();
    var version = string.Empty;

    foreach (var character in temp)
    {
        var validCharacter = false;
        int test = 0;

        if (Int32.TryParse(character.ToString(), out test))
        {
            version += character;
            validCharacter = true;
        }

        if (character == '.' || character == '_')
        {
            version += '.';
            validCharacter = true;
        }

        if (validCharacter == false)
            break;
    }

    return version;
}
Sfax answered 20/8, 2015 at 17:9 Comment(0)
T
20

Use Request.UserAgent

if (Request.UserAgent.IndexOf("Windows NT 5.1") > 0)
{
//xp
}
else if (Request.UserAgent.IndexOf("Windows NT 6.0") > 0)
{
//VISTA
}
else if (Request.UserAgent.IndexOf("Windows NT 6.1") > 0)
{
//7
}
else if (Request.UserAgent.IndexOf("Windows NT 6.2") > 0) 
{ 
//8
}
else if (Request.UserAgent.IndexOf("Windows NT 6.3") > 0) 
{ 
//8.1
}
else if (Request.UserAgent.IndexOf("Windows NT 10.0") > 0) 
{ 
//10
}
Thomasson answered 16/3, 2012 at 9:29 Comment(8)
else if (Request.UserAgent.IndexOf("Windows NT 6.2") > 0) { //8 }Enchain
@mjb, go a head and edit the answer if you are sure about it, I don't have Win 8 to confirmThomasson
else if (Request.UserAgent.IndexOf("Windows NT 6.3") > 0) { //8.1 }Ishmul
updated answer I can't confirm 8 is 6.2 but I think it't very likelyIshmul
@Dreamwalker, thanks for the EDIt, I still can't confirm for Windows 8, But I approved your edit to the answerThomasson
Why not use String.Contains(...)?Bucephalus
@SepehrM, sure that could be used, but I just followed the convention from MSDN article (linked in the question)Thomasson
You're right, just carious why they prefer IndexOf over ContainsBucephalus
G
9

According to This Official Microsoft Document we can use this to detect Windows OS:

String userAgent = Request.UserAgent;

if (userAgent.IndexOf("Windows NT 6.3") > 0)
{
    //Windows 8.1
}
else if (userAgent.IndexOf("Windows NT 6.2") > 0)
{
    //Windows 8
}
else if (userAgent.IndexOf("Windows NT 6.1") > 0)
{
    //Windows 7
}
else if (userAgent.IndexOf("Windows NT 6.0") > 0) 
{ 
    //Windows Vista
}
else if (userAgent.IndexOf("Windows NT 5.2") > 0) 
{ 
    //Windows Server 2003; Windows XP x64 Edition
}
else if (userAgent.IndexOf("Windows NT 5.1") > 0) 
{ 
    //Windows XP
}
else if (userAgent.IndexOf("Windows NT 5.01") > 0) 
{ 
    //Windows 2000, Service Pack 1 (SP1)
}
else if (userAgent.IndexOf("Windows NT 5.0") > 0) 
{ 
    //Windows 2000
}
else if (userAgent.IndexOf("Windows NT 4.0") > 0) 
{ 
    //Microsoft Windows NT 4.0
}
else if (userAgent.IndexOf("Win 9x 4.90") > 0) 
{ 
    //Windows Millennium Edition (Windows Me)
}
else if (userAgent.IndexOf("Windows 98") > 0) 
{ 
    //Windows 98
}
else if (userAgent.IndexOf("Windows 95") > 0) 
{ 
    //Windows 95
}
else if (userAgent.IndexOf("Windows CE") > 0) 
{ 
    //Windows CE
}
else
{ 
    //Others
}
Geaghan answered 24/8, 2014 at 10:24 Comment(0)
P
9

There is a cool tool named: https://github.com/ua-parser/uap-csharp
that parse the user agent to OS,Browser,Browser version etc...
Link to Nuget

And this is how used it:

 public static string GetUserOS(string userAgent)
 {
    // get a parser with the embedded regex patterns
    var uaParser = Parser.GetDefault();
    ClientInfo c = uaParser.Parse(userAgent);
    return c.OS.Family;
 }
Petrolatum answered 8/8, 2016 at 11:50 Comment(1)
Is this your tool?Maggiemaggio
L
7

All In One Class

  public class OS
        {
            public string os_name { get; set; }
            public string os_version { get; set; }

            public OS()
            {
                var ua = HttpContext.Current.Request.UserAgent;
                if (ua.Contains("Android"))
                {
                    this.os_name = "Android";
                    SetVersion(ua, "Android");
                    return;
                }

                if (ua.Contains("iPhone"))
                {
                    this.os_name = "iPhone";
                    SetVersion(ua, "OS");
                    return;
                }

                if (ua.Contains("iPad"))
                {
                    this.os_name = "iPad";
                    SetVersion(ua, "OS");
                    return;
                }

                if (ua.Contains("Mac OS"))
                {
                    this.os_name = "Mac OS";
                    return;
                }

                if (ua.Contains("Windows NT 10"))
                {
                    this.os_name = "Windows";
                    this.os_version = "10";
                    return;
                }

                if (ua.Contains("Windows NT 6.3"))
                {
                    this.os_name = "Windows";
                    this.os_version = "8.1";
                    return;
                }

                if (ua.Contains("Windows NT 6.2"))
                {
                    this.os_name = "Windows";
                    this.os_version = "8";
                    return;
                }


                if (ua.Contains("Windows NT 6.1"))
                {
                    this.os_name = "Windows";
                    this.os_version = "7";
                    return;
                }

                if (ua.Contains("Windows NT 6.0"))
                {
                    this.os_name = "Windows";
                    this.os_version = "Vista";
                    return;
                }

                if (ua.Contains("Windows NT 5.1") || ua.Contains("Windows NT 5.2"))

                {
                    this.os_name = "Windows";
                    this.os_version = "XP";
                    return;
                }

                if (ua.Contains("Windows NT 5"))
                {
                    this.os_name = "Windows";
                    this.os_version = "2000";
                    return;
                }

                if (ua.Contains("Windows NT 4"))
                {
                    this.os_name = "Windows";
                    this.os_version = "NT4";
                    return;
                }

                if (ua.Contains("Win 9x 4.90"))
                {
                    this.os_name = "Windows";
                    this.os_version = "Me";
                    return;
                }

                if (ua.Contains("Windows 98"))
                {
                    this.os_name = "Windows";
                    this.os_version = "98";
                    return;
                }

                if (ua.Contains("Windows 95"))
                {
                    this.os_name = "Windows";
                    this.os_version = "95";
                    return;
                }


                if (ua.Contains("Windows Phone"))
                {
                    this.os_name = "Windows Phone";
                    SetVersion(ua, "Windows Phone");
                    return;
                }

                if (ua.Contains("Linux") && ua.Contains("KFAPWI"))
                {
                    this.os_name = "Kindle Fire";
                    return;
                }

                if (ua.Contains("RIM Tablet") || (ua.Contains("BB") && ua.Contains("Mobile")))
                {
                    this.os_name = "Black Berry";
                    return;
                }

                //fallback to basic platform:
                this.os_name = request.Browser.Platform + (ua.Contains("Mobile") ? " Mobile " : "");
            }

            private void SetVersion(string userAgent, string device)
            {
                var temp = userAgent.Substring(userAgent.IndexOf(device) + device.Length).TrimStart();
                var version = string.Empty;

                foreach (var character in temp)
                {
                    var validCharacter = false;
                    int test = 0;

                    if (Int32.TryParse(character.ToString(), out test))
                    {
                        version += character;
                        validCharacter = true;
                    }

                    if (character == '.' || character == '_')
                    {
                        version += '.';
                        validCharacter = true;
                    }

                    if (validCharacter == false)
                        break;
                }
                this.os_version = version;
            }
        }

Usage

var os = new OS();
os.os_name; // here is os name
os.os_version; // here is os vers
Languet answered 24/1, 2018 at 18:37 Comment(0)
C
3

The VB.NET answer: I include it only because it might be easier to read and understand.

Public Function GetOS() As String
    Dim MyAgent As String = Current.Request.UserAgent
    If MyAgent.IndexOf("Windows NT 10.0") >= 0 Then
        Return "Windows 10"
    ElseIf MyAgent.IndexOf("Windows NT 6.3") >= 0 Then
        Return "Windows 8.1"
    ElseIf MyAgent.IndexOf("Windows NT 6.2") >= 0 Then
        Return "Windows 8"
    ElseIf MyAgent.IndexOf("Windows NT 6.1") >= 0 Then
        Return "Windows 7"
    ElseIf MyAgent.IndexOf("Windows NT 6.0") >= 0 Then
        Return "Windows Vista"
    ElseIf MyAgent.IndexOf("Windows NT 5.2") >= 0 Then
        Return "Windows Server 2003"
    ElseIf MyAgent.IndexOf("Windows NT 5.1") >= 0 Then
        Return "Windows XP"
    ElseIf MyAgent.IndexOf("Windows NT 5.01") >= 0 Then
        Return "Windows 2000 (SP1)"
    ElseIf MyAgent.IndexOf("Windows NT 5.0") >= 0 Then
        Return "Windows 2000"
    ElseIf MyAgent.IndexOf("Windows NT 4.5") >= 0 Then
        Return "Windows NT 4.5"
    ElseIf MyAgent.IndexOf("Windows NT 4.0") >= 0 Then
        Return "Windows NT 4.0"
    ElseIf MyAgent.IndexOf("Win 9x 4.90") >= 0 Then
        Return "Windows ME"
    ElseIf MyAgent.IndexOf("Windows 98") >= 0 Then
        Return "Windows 98"
    ElseIf MyAgent.IndexOf("Windows 95") >= 0 Then
        Return "Windows 95"
    ElseIf MyAgent.IndexOf("Windows CE") >= 0 Then
        Return "Windows CE"
    ElseIf (MyAgent.Contains("iPad")) Then
        Return String.Format("iPad OS {0}", GetMobileVersion(MyAgent, "OS"))
    ElseIf (MyAgent.Contains("iPhone")) Then
        Return String.Format("iPhone OS {0}", GetMobileVersion(MyAgent, "OS"))
    ElseIf (MyAgent.Contains("Linux") AndAlso MyAgent.Contains("KFAPWI")) Then
        Return "Kindle Fire"
    ElseIf (MyAgent.Contains("RIM Tablet") OrElse (MyAgent.Contains("BB") AndAlso MyAgent.Contains("Mobile"))) Then
        Return "Black Berry"
    ElseIf (MyAgent.Contains("Windows Phone")) Then
        Return String.Format("Windows Phone {0}", GetMobileVersion(MyAgent, "Windows Phone"))
    ElseIf (MyAgent.Contains("Mac OS")) Then
        Return "Mac OS"
    ElseIf MyAgent.IndexOf("ANDROID") >= 0 Then
        Return String.Format("Android {0}", GetMobileVersion(MyAgent, "ANDROID"))
    Else
        Return "OS is unknown."
    End If
End Function

Private Function GetMobileVersion(userAgent As String, device As String) As String
    Dim ReturnValue As String = String.Empty
    Dim RawVersion As String = userAgent.Substring(userAgent.IndexOf(device) + device.Length).TrimStart()
    For Each character As Char In RawVersion
        If IsNumeric(character) Then
            ReturnValue &= character
        ElseIf (character = "." OrElse character = "_") Then
            ReturnValue &= "."
        Else
            Exit For
        End If
    Next
    Return ReturnValue
End Function
Cube answered 30/9, 2016 at 16:19 Comment(1)
Frank is right. I changed all the WINDOWS to Windows.Cube
V
3

Try this I just Modify

string device = getOSInfo();

public String getOSInfo()
{
    var ua = Request.UserAgent;

    if (ua.Contains("Android"))
        return string.Format("Android {0}", GetMobileVersion(ua, "Android"));

    if (ua.Contains("iPad"))
        return string.Format("iPad OS {0}", GetMobileVersion(ua, "OS"));

    if (ua.Contains("iPhone"))
        return string.Format("iPhone OS {0}", GetMobileVersion(ua, "OS"));

    if (ua.Contains("Linux") && ua.Contains("KFAPWI"))
        return "Kindle Fire";

    if (ua.Contains("RIM Tablet") || (ua.Contains("BB") && ua.Contains("Mobile")))
        return "Black Berry";

    if (ua.Contains("Windows Phone"))
        return string.Format("Windows Phone {0}", GetMobileVersion(ua, "Windows Phone"));

    if (ua.Contains("Mac OS"))
        return "Mac OS";

    if (ua.Contains("Windows NT 5.1") || ua.Contains("Windows NT 5.2"))
        return "Windows XP";

    if (ua.Contains("Windows NT 6.0"))
        return "Windows Vista";

    if (ua.Contains("Windows NT 6.1"))
        return "Windows 7";

    if (ua.Contains("Windows NT 6.2"))
        return "Windows 8";

    if (ua.Contains("Windows NT 6.3"))
        return "Windows 8.1";

    if (ua.Contains("Windows NT 10"))
        return "Windows 10";

    //fallback to basic platform:
    return (ua.Contains("Mobile") ? " Mobile " : "");
}
public String GetMobileVersion(string userAgent, string device)
{
    var temp = userAgent.Substring(userAgent.IndexOf(device) + device.Length).TrimStart();
    var version = string.Empty;

    foreach (var character in temp)
    {
        var validCharacter = false;
        int test = 0;

        if (Int32.TryParse(character.ToString(), out test))
        {
            version += character;
            validCharacter = true;
        }

        if (character == '.' || character == '_')
        {
            version += '.';
            validCharacter = true;
        }

        if (validCharacter == false)
            break;
    }

    return version;
}
Vaccaro answered 28/4, 2018 at 8:56 Comment(1)
What if the OS is server? For example both Windows 8.1 and Windows Server 2012 R2 are NT 6.3.Asir
S
2

There's no accurate way of doing so as all the information you get from user request's headers which can easily be changed by user and can contain just anything.

If you're OK with reading probably inaccurate information then you may want to check this SO answer to similar question

Steakhouse answered 16/3, 2012 at 9:29 Comment(1)
In my opinion, most users will not even know what request headers are, let alone be actively changing them to mask/hide the platform they are connecting with. Your statement should read: "If you're OK with reading potentially inaccurate information...."Sfax
S
2

Use the version number after "Windows NT". Windows 7 has 6.1 as version number.

But don't rely too much on that, user agent string is non standard. For example look this list, you'll see that someone is using Internet Explorer with Windows 9.0!

Shermanshermie answered 16/3, 2012 at 9:30 Comment(3)
Those might be Microsoft engineers testing new OS ;)Steakhouse
I want it, I'm about to install my new Visual Studio 14.0! :PShermanshermie
Flash forward, I've got 2015, woot.Candlefish
S
2
private string getOS()
{
    string os = null;
    if (Request.UserAgent.IndexOf("Windows NT 5.1") > 0)
    {
        os ="Windows XP";
        return os;
    }
    else if (Request.UserAgent.IndexOf("Windows NT 6.0") > 0)
    {
        os= "Windows Vista";
        return os;
    }
    else if (Request.UserAgent.IndexOf("Windows NT 6.1") > 0)
    {
        os = "Windows 7";
        return os;
    }
    else if (Request.UserAgent.IndexOf("Intel Mac OS X") > 0)
    {
        //os = "Mac OS or older version of Windows";
        os = "Intel Mac OS X";
        return os;
    }
    else
    {
        os = "You are using older version of Windows or Mac OS";
        return os;
    }

}
Scow answered 25/2, 2014 at 16:20 Comment(0)
D
1

John the VB function is nice but the line for Windows 10 does not work because you have "WINDOWS" in uppercase.

It should be same as others i.e.

If MyAgent.IndexOf("Windows NT 10.0") >= 0 Then
        Return "Windows 10"
Delirium answered 11/1, 2017 at 3:52 Comment(0)
S
0

(.NET 6) You can also retrieve the information more genericaly (if it 'Linux', 'Windows', etc) by the user agent platform (which is a default header) in your Request Middleware, like this:

public class RequestMiddleware : IMiddleware
    {
        private readonly IRequestContext _requestContext;

        public RequestMiddleware(IRequestContext requestContext)
        {
            _requestContext = requestContext;
        }

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            _requestContext.UserOperatingSystem = context.Request.Headers["sec-ch-ua-platform"].ToString();

            // ...

            await next(context);
        }
    }
Sailesh answered 30/6, 2022 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.