在C#中获取当前位置(在区域和语言中指定)

San*_*ngh 8 c# localization

如何获取操作系统的区域和语言中指定的机器当前位置?我已经尝试从RegionInfo类中获取它,但它返回按区域和语言的格式下拉列表中指定的位置.

只是为了澄清我的意思,如果您从机器的控制面板打开区域和语言,我想读取位置选项卡中指定的位置.RegionInfo为我提供了格式下拉格式选项卡中指定的值.

San*_*ngh 18

经过大量的谷歌搜索,我终于得到了答案.以下两个链接帮助我获得当前的机器位置 -

http://social.msdn.microsoft.com/Forums/eu/csharpgeneral/thread/6dfaa142-c588-4cb0-b044-fa1e8138b299

http://www.siao2.com/2007/02/21/1733999.aspx

如果有人对最终代码感兴趣,我做了以下实用程序类 -

public static class RegionAndLanguageHelper
{
    #region Constants

    private const int GEO_FRIENDLYNAME = 8;

    #endregion

    #region Private Enums

    private enum GeoClass : int
    {
        Nation = 16,
        Region = 14,
    };

    #endregion

    #region Win32 Declarations

    [DllImport("kernel32.dll", ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    private static extern int GetUserGeoID(GeoClass geoClass);

    [DllImport("kernel32.dll")]
    private static extern int GetUserDefaultLCID();

    [DllImport("kernel32.dll")]
    private static extern int GetGeoInfo(int geoid, int geoType, StringBuilder lpGeoData, int cchData, int langid);

    #endregion

    #region Public Methods

    /// <summary>
    /// Returns machine current location as specified in Region and Language settings.
    /// </summary>
    public static string GetMachineCurrentLocation()
    {
        int geoId = GetUserGeoID(GeoClass.Nation); ;
        int lcid = GetUserDefaultLCID();
        StringBuilder locationBuffer = new StringBuilder(100);
        GetGeoInfo(geoId, GEO_FRIENDLYNAME, locationBuffer, locationBuffer.Capacity, lcid);

        return locationBuffer.ToString().Trim();
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

  • 这是多个操作系统上唯一可行的解​​决方案,如Win7 + Win8.我不明白为什么没有评价...... (2认同)

Man*_*uel 0

是的..但更容易:

CultureInfo info = CultureInfo.CurrentCulture;
Run Code Online (Sandbox Code Playgroud)

  • 那是行不通的。例如,我的位置选项卡设置为日本。但是,上面的代码生成了 en-US。 (2认同)