1 //------------------------------------------------------------------------------
2 // <copyright file="CultureUtil.cs" company="Microsoft">
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 //------------------------------------------------------------------------------
7 namespace System.Web.Util {
9 using System.Globalization;
11 // This class contains helper methods for obtaining a CultureInfo instance from a list of candidates.
13 internal static class CultureUtil {
15 // Given a single culture name, attempts to turn it into a CultureInfo.
16 // If 'requireSpecific' is set, this method attempts to return an object where IsNeutral = false.
17 public static CultureInfo CreateReadOnlyCulture(string cultureName, bool requireSpecific) {
18 if (requireSpecific) {
19 return HttpServerUtility.CreateReadOnlySpecificCultureInfo(cultureName);
22 return HttpServerUtility.CreateReadOnlyCultureInfo(cultureName);
26 // Given a list of culture names, loop through them until we find one we understand.
27 // We expect 'cultureNames' to be the raw Accept-Languages header value, as we'll strip q-values.
28 // Otherwise equivalent to the single-element overload.
29 public static CultureInfo CreateReadOnlyCulture(string[] cultureNames, bool requireSpecific) {
30 return ExtractCultureImpl(cultureNames, requireSpecific, AppSettings.MaxAcceptLanguageFallbackCount);
33 // for unit testing, uses 'maxCount' instead of the <appSettings> switch
34 internal static CultureInfo ExtractCultureImpl(string[] cultureNames, bool requireSpecific, int maxCount) {
35 int lastIndex = Math.Min(cultureNames.Length, maxCount) - 1;
37 for (int i = 0; i < cultureNames.Length; i++) {
38 string candidate = StripQValue(cultureNames[i]);
41 return CreateReadOnlyCulture(candidate, requireSpecific);
43 catch (CultureNotFoundException) {
44 // If this is the last iteration before giving up, let the exception propagate upward.
45 // Otherwise just ---- and move on to the next candidate.
55 // Given an input "foo;q=xx", returns "foo".
56 private static string StripQValue(string input) {
58 int indexOfSemicolon = input.IndexOf(';');
59 if (indexOfSemicolon >= 0) {
60 return input.Substring(0, indexOfSemicolon);