我有用于使用c#设置windows10自动登录的代码, 这段代码写回来了,我希望它能有效。
但是当我现在测试它时,它无法在注册表中设置键值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace engage.client.setup
{
using Microsoft.Win32;
using System;
using System.DirectoryServices;
public class AutoLogin
{
public static void AutoLoginUser()
{
try
{
DirectoryEntry AD = new DirectoryEntry("WinNT://" +
Environment.MachineName + ",computer");
DirectoryEntry NewUser = AD.Children.Add("EngageUser", "user");
NewUser.Invoke("SetPassword", new object[] { "engage" });
NewUser.Invoke("Put", new object[] { "Description", "EngageUser" });
NewUser.CommitChanges();
DirectoryEntry grp;
grp = AD.Children.Find("Administrators", "group");
if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); }
Console.WriteLine("Account Created Successfully...");
RemoveDefaultLogin();
WriteDefaultLogin("EngageUser", "engage");
Console.WriteLine("please restart your system");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("error"+ex.Message);
Console.ReadLine();
}
}
public static void WriteDefaultLogin(string usr, string pwd)
{
Console.WriteLine("Setting autologin...");
RegistryKey rekey = Registry.LocalMachine.CreateSubKey
("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon");
Console.WriteLine("before setting:" + rekey.GetValue("AutoAdminLogon")+ rekey.GetValue("DefaultUserName") + rekey.GetValue("DefaultPassword"));
if (rekey == null)
Console.WriteLine
("There has been an error while trying to write to windows registry");
else
{
rekey.SetValue("mytestingkey", "worked");
rekey.SetValue("AutoAdminLogon", "1");
// Console.WriteLine("set:autoadminlogon:1"+"/n reg set vlaue:"+rekey.GetValue("AutoAdminLogon"));
rekey.SetValue("DefaultUserName", usr);
// Console.WriteLine("set:username"+usr+ "/n reg set vlaue:" + rekey.GetValue("DefaultUserName"));
rekey.SetValue("DefaultPassword", pwd);
// Console.WriteLine("set:password"+ pwd+"/n reg set vlaue :" + rekey.GetValue("DefaultPassword"));
}
Console.WriteLine("after setting" + rekey.GetValue("AutoAdminLogon") + rekey.GetValue("DefaultUserName") + rekey.GetValue("DefaultPassword"));
rekey.Flush();
rekey.Close();
}
public static void RemoveDefaultLogin()
{
RegistryKey rekey = Registry.LocalMachine.CreateSubKey
("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon");
if (rekey == null)
Console.WriteLine("Registry write error");
else
{
rekey.DeleteValue("DefaultUserName", false);
rekey.DeleteValue("DefaultPassword", false);
rekey.DeleteValue("AutoAdminLogon", false);
}
rekey.Close();
}
}
}
为什么即使getvalue方法显示更新的值,我也无法更改密钥,在注册表中它没有更新。
答案 0 :(得分:0)
除非您的程序以管理员身份运行,否则您无法更新Registry.LocalMachine
个条目。您需要在程序中添加清单make it require administrator privileges to launch。
您可能还有32位程序试图访问64位regestery密钥。将Registry.LocalMachine
替换为Registry.LocalMachine(RegistryHive.LocalMachine, RegistryView.Registry64)
以强制它使用64位注册表,即使您的应用程序以32位运行。
您还可以将程序编译为64位而不是32位或AnyCpu,以强制它为64位。