Попытка развернуть небольшое приложение, которое вносит изменения в реестр - PullRequest
1 голос
/ 18 мая 2011

У меня есть следующая программа, и когда я ее собираю (Release config). Он работает на моей машине разработчика в качестве администратора. Однако, когда я запускаю его на Конечном Пользователе (не администраторе), он вылетает и говорит что-то о Безопасности. Есть ли что-то, что мне нужно сделать в свойствах (или в коде), чтобы он мог маскироваться под администратора

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace LotusTrustedSites
{       
    class ReportDownloader    
    {        
        [STAThread]        
        static void Main(string[] args)        
        {            
            const string domainsKeyLocation = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains";            
            const string domain = @"newsite.com";            
            const int trustedSiteZone = 0x2;            
            var subdomains = new Dictionary<string, string>
                {                                     
                    {"www", "https"},                                     
                    {"www", "http"},                                     
                    {"blog", "https"},                                     
                    {"blog", "http"}                                 
                };            
            RegistryKey currentUserKey = Registry.CurrentUser;            
            currentUserKey.GetOrCreateSubKey(domainsKeyLocation, domain, false);            
            foreach (var subdomain in subdomains)            
            {                
                CreateSubdomainKeyAndValue(currentUserKey, domainsKeyLocation, domain, subdomain, trustedSiteZone);            
            }            //automation code        
        }        

        private static void CreateSubdomainKeyAndValue(RegistryKey currentUserKey, string domainsKeyLocation, string domain, KeyValuePair<string, string> subdomain, int zone)        
        {            
            RegistryKey subdomainRegistryKey = currentUserKey.GetOrCreateSubKey(string.Format(@"{0}\{1}", domainsKeyLocation, domain), subdomain.Key, true);            
            object objSubDomainValue = subdomainRegistryKey.GetValue(subdomain.Value);            
            if (objSubDomainValue == null || Convert.ToInt32(objSubDomainValue) != zone)            
            {                
                subdomainRegistryKey.SetValue(subdomain.Value, zone, RegistryValueKind.DWord);            
            }        
        }    
    }    
    public static class RegistryKeyExtensionMethods    
    {        
        public static RegistryKey GetOrCreateSubKey(this RegistryKey registryKey, string parentKeyLocation, string key, bool writable)        
        {            
            string keyLocation = string.Format(@"{0}\{1}", parentKeyLocation, key);           
            RegistryKey foundRegistryKey = registryKey.OpenSubKey(keyLocation, writable);            
            return foundRegistryKey ?? registryKey.CreateSubKey(parentKeyLocation, key);        
        }        
        public static RegistryKey CreateSubKey(this RegistryKey registryKey, string parentKeyLocation, string key)        
        {            
            RegistryKey parentKey = registryKey.OpenSubKey(parentKeyLocation, true); //must be writable == true            
            if (parentKey == null) 
            { 
                throw new NullReferenceException(string.Format("Missing parent key: {0}", parentKeyLocation)); 
            }            
            RegistryKey createdKey = parentKey.CreateSubKey(key);            
            if (createdKey == null) 
            { 
                throw new Exception(string.Format("Key not created: {0}", key)); 
            }            
            return createdKey;        
        }    
    }
}

Ответы [ 3 ]

3 голосов
/ 18 мая 2011

Эта статья может помочь.

2 голосов
/ 18 мая 2011

Запись в реестр является привилегированной операцией - вам необходимо иметь соответствующие разрешения.

У учетной записи, под которой работает приложение, должны быть соответствующие разрешения.

0 голосов
/ 18 мая 2011

Создание настроек реестра программным способом - неправильная вещь. Проблема заключается в том, что подсистема установщика Windows не может отслеживать эти записи, а также восстанавливать или удалять их по мере необходимости. Лучше выбрать файл настроек приложения или предоставить установщик MSI, который создает эти записи для вас.

...