如何获得在 C# 中编辑 app.config 的管理员权限? [英] How to get admin privileges for editing app.config in C#?

查看:33
本文介绍了如何获得在 C# 中编辑 app.config 的管理员权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a program which uses app.config for storing some preferences. The problem is that if the program is installed in C:\program files\<project name> then the changing of preferences is not possible due to the fact that all files in program files\<project name> are available only to administrator.

我的代码:

    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;
    }

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

The question is: Is there a way how to elevate privileges for this action? Or how else to solve the problem?

谢谢!

推荐答案

全局 app.config 文件(用于 EXE)通常不打算由使用它们的程序编辑 - 通常由安装程序等进行编辑.您可能想要的只是用户设置(更改范围).它们通常存储在 AppData 中,更好的是,设置的代理属性是自动生成的,因此您可以执行以下操作:

Global app.config files (for EXEs) generally aren't meant to be edited by the program that uses them - more typically by installers and the like. What you probably want is simply User Settings (a simple matter of changing the scope). They generally get stored in AppData, and even better, proxy properties for the settings are auto-generated, so you can do something like:

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

这就是(几乎)我在管理设置时需要做的所有事情!

This is (pretty much) all I've ever needed to do when managing settings!

这篇关于如何获得在 C# 中编辑 app.config 的管理员权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆