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

Mar*_*cka 1 c# privileges app-config

我有一个程序,它使用app.config存储一些首选项.问题是,如果程序安装在C:\ program files\<项目名称>中,则由于程序文件\ <项目名称>中的所有文件仅供管理员使用,因此无法更改首选项.

我的代码:

    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;
    }
Run Code Online (Sandbox Code Playgroud)

问题是:有没有办法提升这个行动的特权?或者如何解决问题呢?

谢谢!

Nol*_*rin 9

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

Properties.Settings.Default.Foo = "bar";
Properties.Settings.Default.Save();
Run Code Online (Sandbox Code Playgroud)

这是(几乎)我在管理设置时所需要做的一切!