无法删除C#中的注册表文件夹

时间:2015-10-09 04:04:14

标签: c# winforms

我正在尝试使用C#代码删除注册表文件夹,但它会引发异常I.e.钥匙不存在...... !!! 但是如果key不存在那么注册表对象应该如何不为null 但在这种情况下,它将它显示为null,它包含一些值 这是我的代码

bool IsDeleted = false;
            try
            {
                regkey = regkey.Replace(@"HKEY_LOCAL_MACHINE\", "");
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(regkey, true))
                {
                    if (key != null)//here it show that key is exists
                    {
                        IsDeleted = DeleteKey(key, regkey);//in this line It generate exception

                    }
                }
            }
            catch
            {
            }
             return IsDeleted;

这是删除代码

 public static bool DeleteKey(RegistryKey hKey, string strPath)
        {
            bool flag1 = false;
            int num1 = 0;
            int num2 = 0;
            try
            {
                num2 = 1;
                hKey.DeleteSubKeyTree(strPath);
                flag1 = true;
            }
            catch (Exception obj1) //when (?)
            {
                Exception exception2 = (Exception)obj1;
                Exception exception1 = exception2;
                if (num1 == 0)
                {
                    num1 = -1;
                    switch (num2)
                    {
                        case 1:
                            {
                                goto Label_0058;
                            }
                    }
                    throw;
                }
            }
        Label_0058:
            if (num1 != 0)
            {
            }
            return flag1;
        }

请帮帮我 日Thnx

1 个答案:

答案 0 :(得分:-1)

由于Windows 7中的权限问题而发生这种情况

try
            {
                new System.Security.Permissions.RegistryPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
                hKey.DeleteSubKeyTree(strPath);
                flag1 = true;
            }
            catch (Exception obj1) //when (?)
            {
            }
            finally
            {
                System.Security.Permissions.RegistryPermission.RevertAssert();
            } 

您可以将此清单嵌入到您的应用程序中。

<?xml version="1.0" encoding="utf-8" ?> 
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <assemblyIdentity version="1.0.0.0" name="MyApplication" />
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
            <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
                <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
            </requestedPrivileges>
        </security>
    </trustInfo>
</asmv1:assembly>