C# Auto Detect Preferred Country

I found that IP to Country has not been that best practices in locating that visitor preferred country, mostly because of IP are allocated to ISP in there registered country, but where the actual user with that assign IP address can be anywhere (also the VPN). Therefore a better way to detect that website visitor is to check their actual browser preferred language and country, this is done by the Request.UserLanguages in C#, but due to that this property return with a array of language that the visitor browser is set to, therefore not just one country is return. So I would need way to query this array and return only the country short code.

Here I created a function to do just that;

    public static string DetectCountry(string[] UserLanguages)
    {
        for (int i = 0; i < UserLanguages.Length; i++)
            UserLanguages[i] = UserLanguages[i].Substring(UserLanguages[i].IndexOf('-') + 1, 2);
        if (UserLanguages.Length == 0)
            return "US";
        if (UserLanguages.Length > 1)
            if (UserLanguages[1] != "US")
                return UserLanguages[1];
            else
                return UserLanguages[0];
        else
            return UserLanguages[0];
    }

And when you use it you just call the with Request.UserLanguages property as it parameter;

string CountryCode = DetectCountry(Request.UserLanguages);

Now that you use the country short code in any why you want.

  • Adeeb
  • http://www.sarin.mobi Sarin Na Wangkanai
  • http://www.sarin.mobi Sarin Na Wangkanai