代码之家  ›  专栏  ›  技术社区  ›  MartyIX

如何获得在C#中编辑app.config的管理员权限?

  •  1
  • MartyIX  · 技术社区  · 14 年前

    C:\程序文件\<项目名称> 由于所有文件都在 程序文件\<项目名称> 仅对管理员可用。

    我的代码:

        public static bool EditKeyPair(string key, string value)
        {
            bool success = true;
    
            // Open App.Config of executable
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            KeyValueConfigurationCollection settings = config.AppSettings.Settings;
    
            // update SaveBeforeExit
            settings[key].Value = value;
    
            if (!config.AppSettings.SectionInformation.IsLocked)
            {
                //save the file
                config.Save(ConfigurationSaveMode.Modified);
                Debug.WriteLine("** Settings updated.");
            }
            else
            {
                Debug.WriteLine("** Could not update, section is locked.");
                success = false;
            }
    
            //reload the section you modified
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
    
            return success;
        }
    

    问题是:有没有办法提升此操作的权限?或者如何解决这个问题?

    谢谢您!

    3 回复  |  直到 14 年前
        1
  •  9
  •   Noldorin    14 年前

    全局app.config文件(对于exe)通常不打算由使用它们的程序进行编辑,更典型的是由安装程序等进行编辑。你可能想要的只是 User Settings (一个简单的改变范围的问题)。它们通常储存在 AppData ,更好的是,设置的代理属性是自动生成的,因此您可以执行以下操作:

    Properties.Settings.Default.Foo = "bar";
    Properties.Settings.Default.Save();
    

        2
  •  3
  •   Sky Sanders    14 年前

    通常,如果一个应用程序通常不需要提升,那么您可以将需要提升的功能分解为一个由开关控制的模式,然后使用runas动词启动它自己。

    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.UseShellExecute = true;
    startInfo.WorkingDirectory = Environment.CurrentDirectory;
    startInfo.FileName = Application.ExecutablePath;
    startInfo.Arguments = "-doSomethingThatRequiresElevationAndExit";
    startInfo.Verb = "runas";
    try
    {
        Process p = Process.Start(startInfo);
        p.WaitForExit();
    
    }
    catch(System.ComponentModel.Win32Exception ex)
    {
        return;
    }
    

    appData

        3
  •  0
  •   Dean Harding    14 年前

    在项目属性中,将这些设置从Scope=Application更改为Scope=User。这样,它们就存储在用户的配置文件中,您不需要管理员权限来修改它们。