開機自啟動程序如下:
if (!System.IO.File.Exists(filename))
throw new Exception("該文件不存在!");
string name = filename.Substring(filename.LastIndexOf("\\") + 1);
reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (reg == null)
{
reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
}
if (isAutoRun)
reg.SetValue(name, filename);
else
reg.SetValue(name, false);
然后彈出異常:securityexception不允許所請求的注冊表訪問權。
找了好久都說什么權限不夠,不是我需要的答案。解決方法如下:
1、右鍵生成的exe應用程序,以管理員身份運行,如果沒問題,就說明是可以訪問修改注冊表的;
但是這樣是不能用的,因為你重啟后會直接彈出異常,說不允許所請求的注冊表訪問權 。問題還是沒解決。
2、一般在win7下,VS訪問注冊表HKEY_LOCAL_MACHINE,即程序中的LocalMachine是需要管理員身份運行的。但是訪問HKEY_CURRENT_USER是沒問題的。
所以修改程序如下:
...
reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (reg == null)
{
reg = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
}
...
OK,可以了