“RegEnumKeyEx”返回空字符串数组(C#invoke)

时间:2011-04-29 07:32:26

标签: c# registry

我必须在Registry分支中获取子键列表和值列表。

[DllImport("advapi32.dll", EntryPoint="RegEnumKeyExW",
            CallingConvention=CallingConvention.Winapi)]
[MethodImpl(MethodImplOptions.PreserveSig)]
extern private static int RegEnumKeyEx(IntPtr hkey, uint index,
                        char[] lpName, ref uint lpcbName,
                            IntPtr reserved, IntPtr lpClass, IntPtr lpcbClass,
                        out long lpftLastWriteTime);


// Get the names of all subkeys underneath this registry key.
public String[] GetSubKeyNames()
{
    lock(this)
    {
        if(hKey != IntPtr.Zero)
        {
            // Get the number of subkey names under the key.
            uint numSubKeys, numValues;
            RegQueryInfoKey(hKey, null,IntPtr.Zero, IntPtr.Zero,out numSubKeys, IntPtr.Zero, IntPtr.Zero, out numValues,IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            // Create an array to hold the names.
            String[] names = new String [numSubKeys];
            StringBuilder sb = new StringBuilder();
            uint MAX_REG_KEY_SIZE = 1024;
            uint index = 0;
            long writeTime;
            while (index < numSubKeys)
            {
                sb = new StringBuilder();
                if (RegEnumKeyEx(hKey,index,sb,ref MAX_REG_KEY_SIZE, IntPtr.Zero,IntPtr.Zero,IntPtr.Zero,out writeTime) != 0)
                {
                    break;
                }
                names[(int)(index++)] = sb.ToString();
            }
            // Return the final name array to the caller.
            return names;
        }
        return new String [0];
    }
}

它现在运作良好,但仅适用于第一个元素。它返回0索引的键名,但对于其他它返回“”。

怎么可能?

顺便说一句:我用你的定义取代了你的定义,工作得很好

2 个答案:

答案 0 :(得分:3)

RegEnumKeyEx的P / Invoke定义是什么?

也许,试试这个:

[DllImport("advapi32.dll", EntryPoint = "RegEnumKeyEx")]
extern private static int RegEnumKeyEx(UIntPtr hkey,
    uint index,
    StringBuilder lpName,
    ref uint lpcbName,
    IntPtr reserved,
    IntPtr lpClass,
    IntPtr lpcbClass,
    out long lpftLastWriteTime);
来自pinvoke.net站点的

采用stringbuilder而不是字符数组。这将排除您未显示的代码中的潜在错误,例如ArrayToString和P / Invoke定义中您也未显示的错误。

答案 1 :(得分:1)

为什么要使用P / Invoke?您可以使用Registry类来代替......

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SomeKey"))
{
    string[] subKeys = key.GetSubKeyNames();
    string[] valueNames = key.GetValueNames();
    string myValue = (string)key.GetValue("myValue");
}