如何从注册表中获取重定向的字符串?

时间:2014-03-08 19:28:01

标签: c# localization registry

我正在使用Registry从注册表中读取一些值。我需要访问的一些值使用Registry String Redirection

这种包含值的一个例子是:

@%SystemRoot%\system32\shell32.dll,-21791

如何访问此本地化字符串?

1 个答案:

答案 0 :(得分:4)

.NET库中似乎没有内置方法来执行此操作,但是as this C++ answer shows,您可以在RegLoadMUIStringadvapi32.dll中调用Windows API

您可以在下面找到RegistryKey的扩展方法,它可以通过跟踪字符串重定向来加载值。

/// <summary>
///   Retrieves the multilingual string associated with the specified name. Returns null if the name/value pair does not exist in the registry.
///   The key must have been opened using 
/// </summary>
/// <param name = "key">The registry key to load the string from.</param>
/// <param name = "name">The name of the string to load.</param>
/// <returns>The language-specific string, or null if the name/value pair does not exist in the registry.</returns>
public static string LoadMuiStringValue( this RegistryKey key, string name )
{
    const int initialBufferSize = 1024;
    var output = new StringBuilder( initialBufferSize );
    int requiredSize;
    IntPtr keyHandle = key.Handle.DangerousGetHandle();
    ErrorCode result = (ErrorCode)AdvApi32.RegLoadMUIString( keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null );

    if ( result == ErrorCode.MoreData )
    {
        output.EnsureCapacity( requiredSize );
        result = (ErrorCode)AdvApi32.RegLoadMUIString( keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null );
    }

    return result == ErrorCode.Success ? output.ToString() : null;
}

所需的COM导入是:

// Snippet of ErrorCode.
enum ErrorCode
{
    Success = 0x0000,
    MoreData = 0x00EA
}

[DllImport( Dll, CharSet = CharSet.Unicode )]
public extern static int RegLoadMUIString(
    IntPtr registryKeyHandle, string value,
    StringBuilder outputBuffer, int outputBufferSize, out int requiredSize,
    RegistryLoadMuiStringOptions options, string path );

/// <summary>
///   Determines the behavior of <see cref="RegLoadMUIString" />.
/// </summary>
[Flags]
internal enum RegistryLoadMuiStringOptions : uint
{
    None = 0,
    /// <summary>
    ///   The string is truncated to fit the available size of the output buffer. If this flag is specified, copiedDataSize must be NULL.
    /// </summary>
    Truncate = 1
}

请记住,这只适用于Vista及更高版本!