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
I think there's no such method. So you could just try-catch
or check all installed cultures:
string cultureCode = "de-DE";
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
var culture = cultures.FirstOrDefault(c => c.Name.Equals(cultureCode, StringComparison.OrdinalIgnoreCase));
if (culture == null)
{
culture = cultures.FirstOrDefault(c => c.Name.Equals(DefaultCultureCode, StringComparison.OrdinalIgnoreCase));
if (culture == null)
culture = CultureInfo.CurrentCulture;
}
But i would prefer the try-catch
, i'm sure it is more efficient.
public bool TryGetCultureInfo(string cultureCode, string DefaultCultureCode, out CultureInfo culture)
{
try
{
culture = CultureInfo.GetCultureInfo(cultureCode);
return true;
} catch(CultureNotFoundException)
{
if (DefaultCultureCode == null)
culture = CultureInfo.CurrentCulture;
else
{
try
{
culture = CultureInfo.GetCultureInfo(DefaultCultureCode);
} catch (CultureNotFoundException)
{
culture = CultureInfo.CurrentCulture;
}
}
}
return false;
}