How to check exists culture in .NET

前端 未结 4 1745
生来不讨喜
生来不讨喜 2021-01-17 08:39

I have this code, when I try to get not existed culture I get exception.
Is there exists method like TryGetCultureInfo, which return bool val

4条回答
  •  迷失自我
    2021-01-17 09:35

    No, AFAIK is not possible. You can check first if the culture exists and in that case get it.

    The following code shows how to do it:

        private static CultureInfo GetCulture(string name)
        {
            if (!CultureExists(name)) return null;
    
            return CultureInfo.GetCultureInfo(name);
        }
    
        private static bool CultureExists(string name)
        {
            CultureInfo[] availableCultures =
                CultureInfo.GetCultures(CultureTypes.AllCultures);
    
            foreach (CultureInfo culture in availableCultures)
            {
                if (culture.Name.Equals(name))
                    return true;
            }
    
            return false;
        }
    

    Hope it helps

提交回复
热议问题