模拟管理员账户编辑注册表项不起作用(C#)配置单元注册表项('SOFTWAREMicrosoftWindowsNTCurrentVersionProfileList%SID%')。一切似乎都很好,直到我真正尝试打开注册表项(具有写权限);抛出SecurityException并显示消息“不允许请求的注册表访问”。我检查并重新检查了注册表项和我正在模拟的用户的权限,他们都检查过了。该代码在登录到模拟用户的帐户时工作正常,但在以受限用户身份登录时失败。这有点像模仿,只是给了线程管理权。stringKEY_STR="SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ProfileList\"+WindowsIdentity.GetCurrent().User.Value;WindowsImpersonationContextadminContext=null;IntPtrtokenHandle=newIntPtr(0);尝试{LogonUser(用户名、域名、密码、LOGON32_LOGON_INTERACTIVE、LOGON32_PROVIDER_DEFAULT、reftokenHandle);如果(tokenHandle.Equals(newIntPtr(0)))LogonUser(userName,computerName,password,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,reftokenHandle);WindowsIdentityadminIdentity=newWindowsIdentity(tokenHandle);adminContext=adminIdentity.Impersonate();RegistryKeykey=Registry.LocalMachine.OpenSubKey(KEY_STR,true);key.SetValue("状态",0x60001);Console.Out.WriteLine("用户配置文件更改为必填。");}catch(Exceptionex){Console.Out.WriteLine("nUnabletosetprofiletoMandatory:nt"+ex.Message);}最后{adminContext.Undo();如果(tokenHandle!=IntPtr.Zero)CloseHandle(tokenHand乐);我知道这篇文章很旧,也许你已经解决了这个问题,但我这样做并且在Win7机器上没有问题:stringuserName="domain\user";//实际上只有一个斜线,//但如果硬编码,则必须将其转义。//如果由文本框引入,则它只是domainuserstringpassword="whatever";字符串KEY_STR="SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ProfileList\"+WindowsIdentity.GetCurrent().User.Value;WindowsImpersonationContextadminContext=Impersonation.getWic(userName,password);if(adminContext!=null){try{RegistryKeykey=Registry.LocalMachine.OpenSubKey(KEY_STR,true);//注意:如果这是在远程机器上,那一行只是://RegistryKeykey=RegistryKey.OpenRemoteSubKey(RegistryHive.LocalMachine,computerName).OpenSubKey(KEY_STR,true);key.SetValue("状态",0x60001);Console.Out.WriteLine("用户配置文件更改为必填。");}catch(Exceptionex){Console.Out.WriteLine("nUnabletosetprofiletoMandatory:nt"+ex.Message);模仿n.endImpersonation();adminContext.Undo();}最后{Impersonation.endImpersonation();//上面的行做了你所拥有的,这里--//if(tokenHandle!=IntPtr.Zero)CloseHandle(tokenHandle);adminContext.Undo();这是我单独的Impersonation类,它有2个主要入口点,getWic()和doImpersonation()-getWic()将采用看起来像domainuser或machinenameuser的内容并将它们交给doImpersonation(),然后再将它们拆分成它们的组成部分,而doImpersonation()接受已经拆分的部分,如果你有这样的部分并且不需要getWic()的代码。两者都返回WindowsImpersonationContext。使用系统;使用系统数据;使用系统配置;使用System.Security.Permissions;使用System.Security.Principal;使用System.Runtime.InteropServices;[程序集:SecurityPermissionAttribute(SecurityAction.RequestMinimum,UnmanagedCode=true)][程序集:PermissionSetAttribute(SecurityAction.RequestMinimum,Name=“FullTrust”)]公共类模拟{[DllImport(“advapi32.dll”,EntryPoint=“LogonUser”)]publicstaticexternboolLogonUser(stringlpszUsername,stringlpszDomain,stringlpszPassword,intdwLogonType,intdwLogonProvider,refIntPtrphToken);[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]publicexternstaticboolDuplicateToken(IntPtrExistingTokenHandle,intSECURITY_IMPERSONATION_LEVEL,refIntPtrDuplicateTokenHandle);[DllImport("kernel32.dll",CharSet=CharSet.Auto)]publicexternstaticboolCloseHandle(IntPtrhandle);//将登录类型声明为常量constintLOGON32_LOGON_INTERACTIVE=2;constintLOGON32_LOGON_NETWORK=3;constintLOGON32_LOGON_BATCH=4;constintLOGON32_LOGON_SERVICE=5;constintLOGON32_LOGON_UNLOCK=7;constintLOGON32_LOGON_NETWORK_CLEARTEXT=8;//Win2K或更高版本constintLOGON32_LOGON_NEW_CREDENTIALS=9;//Win2K或更高版本//将登录提供程序声明为常量constintLOGON32_PROVIDER_DEFAULT=0;constintLOGON32_PROVIDER_WINNT50=3;constintLOGON32_PROVIDER_WINNT40=2;constintLOGON32_PROVIDER_WINNT35=1;//将模拟级别声明为常量constintSecurityAnonymous=0;constintSecurityIdentification=1;constintSecurityImpersonation=2;constintSecurityDelegation=3;私有静态WindowsIdentitynewId;私有静态IntPtrtokenHandle=newIntPtr(0);privatestaticIntPtrdupeTokenHandle=newIntPtr(0);[PermissionSetAttribute(SecurityAction.Demand,Name="FullTrust")]publicstaticWindowsImpersonationContextdoImpersonation(stringsvcUserName,stringdomainName,stringpassword){//初始化令牌tokenHandle=IntPtr.Zero;dupeTokenHandle=IntPtr.Zero;//调用LogonUser以获取访问令牌的句柄boolreturnValue=LogonUser(svcUserName,domainName,password,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_WINNT50,reftokenHandle);如果(returnValue==false){intret=Marshal.GetLastWin32Error();//检查错误if(ret!=NO_ERROR)thrownewException("LogonUserfailedwitherrorcode:"+GetError(ret));}boolretVal=DuplicateToken(tokenHandle,SecurityImpersonation,refdupeTokenHandle);如果(retVal==false){CloseHandle(tokenHandle);thrownewException("尝试复制令牌时抛出异常。");}else{//开始模拟boolbRetVal=DuplicateToken(tokenHandle,(int)SecurityImpersonation,refdupeTokenHandle);newId=newWindowsIdentity(dupeTokenHandle);WindowsImpersonationContextimpersonatedUser=newId.Impersonate();返回模拟用户;}}publicstaticvoidendImpersonation(){if(dupeTokenHandle!=IntPtr.Zero)CloseHandle(dupeTokenHandle);如果(tokenHandle!=IntPtr.Zero)CloseHandle(tokenHandle);}publicstaticWindowsImpersonationContextgetWic(stringuserNameStringFromTextbox,stringpassword){try{//建立模拟stringsvcUser=userNameStringFromTextbox;字符串[]arrUser=新字符串[2];arrUser=svcUser.Split('\');字符串域=arrUser[0];字符串svcUserName=arrUser[1];//获取密码:从Base-64字符串转换为解密字符串//stringkeyLength=ConfigurationManager.AppSettings["keyLength"].ToString();//字符串keyLocation=ConfigurationManager.AppSettings["keyLocation"].ToString();//密码=RSAEncrypt.DecryptData(密码,keyLength,keyLocation);WindowsImpersonationContextwic=doImpersonation(svcUserName,域,密码);返回wic;}catch(Exceptionex){ErrorLog.ErrorRoutine(newException("getWic()错误:"+ex.ToString()),ErrorMessage.NOTIFY_APP_ERROR);returnnull;}}#regionErrorsconstintNO_ERROR=0;constintERROR_ACCESS_DENIED=5;constintERROR_ALREADY_ASSIGNED=85;constintERROR_BAD_DEVICE=1200;constinterror_bad_net_name=67;constinterror_bad_provider=1204;constinterror_cancelled=1223;constinterror_extended_error=1208;constintInterror_invalid_address=487;constintintintintintint;constintint;constintrordor_invalid_paramer_contror_contintrord_intintint;constintrorr_invalir_invalid=87;constint;constint;constint;constint;intERROR_NO_MORE_ITEMS=259;constintERROR_NO_NET_OR_BAD_PATH=1203;constintERROR_NO_NETWORK=1222;constintERROR_SESSION_CREDENTIAL_CONFLICT=1219;constintERROR_BAD_PROFILE=1206;constintERROR_CANNOT_OPEN_PROFILE=1205;constintERROR_DEVICE_IN_USE=2404;constintERROR_NOT_CONNECTED=2250;constintERROR_OPEN_FILES=2401;privatestructErrorClass{publicintnum;publicstringmessage;publicErrorClass(intnum,stringmessage){this.num=num;this.message=消息;}}privatestaticErrorClass[]ERROR_LIST=newErrorClass[]{newErrorClass(ERROR_ACCESS_DENIED,"Error:AccessDenied"),newErrorClass(ERROR_ALREADY_ASSIGNED,"Error:AlreadyAssigned"),newErrorClass(ERROR_BAD_DEVICE,"Error:BadDevice""),newErrorClass(ERROR_BAD_NET_NAME,"Error:BadNetName"),newErrorClass(ERROR_BAD_PROVIDER,"Error:BadProvider"),newErrorClass(ERROR_CANCELLED,"Error:Cancelled"),newErrorClass(ERROR_EXTENDED_ERROR,"Error:扩展错误"),newErrorClass(ERROR_INVALID_ADDRESS,"错误:无效地址"),newErrorClass(ERROR_INVALID_PARAMETER,"错误:无效参数"),newErrorClass(ERROR_INVALID_PASSWORD,"错误:无效密码"),newErrorClass(ERROR_MORE_DATA,"错误:更多数据”),newErrorClass(ERROR_NO_MORE_ITEMS,“错误:没有更多项目”),newErrorClass(ERROR_NO_NET_OR_BAD_PATH,“错误:没有网络或错误路径”),newErrorClass(ERROR_NO_NETWORK,“错误:无网络”),新的ErrorClass(ERROR_SESSION_CREDENTIAL_CONFLICT,“错误:凭证冲突”),新的ErrorClass(ERROR_BAD_PROFILE,“错误:错误的配置文件”),新的ErrorClass(ERROR_CANNOT_OPEN_PROFILE,“错误:可以配置文件”)新的ErrorClass(ERROR_DEVICE_IN_USE,"错误:设备正在使用"),newErrorClass(ERROR_NOT_CONNECTED,"错误:未连接"),newErrorClass(ERROR_OPEN_FILES,"错误:打开文件"),};privatestaticstringGetError(interrNum){foreach(ERROR_LIST中的ErrorClasser){if(er.num==errNum)returner.message;}返回“错误:未知”+errNum;}#endregion}只是猜测,但你碰巧在vista或win7盒子上打开UAC?我希望您获得用户确认以提升权限来执行此操作我的令牌不足以获得对注册表的写访问权限。我会使用作为系统运行的Windows服务来实现这一点。以上就是C#学习教程:模拟管理员账户编辑注册表项不起作用(C#)分享的全部内容。网络收藏不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: