无法在c#中删除注册表文件夹
本文关键字:删除 注册表 文件夹 | 更新日期: 2023-09-27 18:16:47
我试图使用c#代码删除注册表文件夹,但它抛出一个异常,即键不存在…!!但是如果key不存在,那么注册表对象不应该是空的但在这个例子中,它没有显示为空,它包含了一些值这是我的代码
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;
}
请帮我一下非常感谢
这是由于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>