[英]C# UnauthorizedAccessException on RegistryKey CreateSubKey
每當我嘗試在代碼中調用CreateSubKey 時,都會收到UnauthorizedAccessException 異常。
const string regKeyPath = @"Software\Apps\jp2code.net\FTMaint";
private void BuildRegistry() {
string[] split = regKeyPath.Split('\\');
keyMaker(Registry.LocalMachine, split, 0);
}
private static void keyMaker(RegistryKey key, string[] path, int index) {
string keyValue = path[index++];
RegistryKey key2;
if (!String.IsNullOrEmpty(keyValue)) {
string subKey = null;
string[] subKeyNames = key.GetSubKeyNames();
foreach (var item in subKeyNames) {
if (keyValue == item) {
subKey = item;
}
}
if (String.IsNullOrEmpty(subKey)) {
key2 = key.CreateSubKey(keyValue);
} else {
key2 = key.OpenSubKey(subKey);
}
//key2 = key.OpenSubKey(keyValue, String.IsNullOrEmpty(subKey));
} else {
key2 = key;
}
if (index < path.Length) {
try {
keyMaker(key2, path, index + 1);
} finally {
key2.Close();
}
}
}
我在 MSDN Social 上找到了一個帖子,其中有人遇到了類似的問題>> HERE << ,但是那里的解決方案(使用重載的 OpenSubKey 方法)只為我返回了一個 NULL RegistryKey 。
這是用於 Windows Mobile 5 設備模擬器。
誰能看到我做錯了什么?
代碼第一次到達不存在的鍵並嘗試創建它時會拋出錯誤。
謝謝!
所有這三個在 WinMo 6 模擬器上對我來說都很好。
創建根密鑰:
using (var swKey = Registry.LocalMachine.CreateSubKey("foo"))
{
using (var subkey = swKey.CreateSubKey("OpenNETCF"))
{
}
}
通過路徑創建子項
using (var swKey = Registry.LocalMachine.CreateSubKey("software\\foo"))
{
using (var subkey = swKey.CreateSubKey("OpenNETCF"))
{
}
}
直接創建子鍵:
using (var swKey = Registry.LocalMachine.OpenSubKey("software", true))
{
using (var subkey = swKey.CreateSubKey("OpenNETCF"))
{
}
}
我在通過Registry.CurrentUser.OpenSubKey
創建RegistryKey
實例時發現它是只讀的。 所以我可以調用GetValue
但是當我嘗試調用SetValue
我得到了UnauthorizedAccessException
。 訣竅是調用Registry.CurrentUser.OpenSubKey
將可寫參數設置為 true,然后調用SetValue
成功。
所以而不是:
key2 = key.OpenSubKey(subKey);
采用:
key2 = key.OpenSubKey(subKey, writable: true);
這可能同樣適用於對CreateSubKey
的調用。
最初的問題是在 Windows Mobile 的上下文中提出的。 我沒有使用過 Windows Mobile(現在不確定是否有人使用過),但我希望可寫參數會在那里。
要在安裝期間在 LocalMachine 中創建密鑰,請執行以下操作:
[RunInstaller(true)]
public class InstallRegistry : Installer
{
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
using (RegistryKey key = Registry.LocalMachine.CreateSubKey(@"software\..."))
{
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), RegistryRights.FullControl, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
key.SetAccessControl(rs);
}
}
public override void Rollback(System.Collections.IDictionary savedState)
{
base.Rollback(savedState);
}
}
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.