簡體   English   中英

如何獲得在C#中編輯app.config的管理員特權?

[英]How to get admin privileges for editing app.config in C#?

我有一個程序使用app.config來存儲一些首選項。 問題是,如果程序安裝在C:\\ program files \\ <項目名稱>中,則由於程序文件\\ <project name>中的所有文件僅對管理員可用,因此無法更改首選項。

我的代碼:

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

問題是:是否有辦法提高此操作的特權? 還是要怎么解決這個問題?

謝謝!

全局app.config文件(用於EXE)通常並不意味着由使用它們的程序進行編輯-更通常是由安裝程序等進行編輯。 您可能只需要用戶設置 (更改范圍的簡單問題)。 它們通常存儲在AppData ,甚至更好,設置的代理屬性是自動生成的,因此您可以執行以下操作:

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

這(幾乎)是我在管理設置時需要做的所有事情!

要按原樣回答您的問題,沒有辦法“暫時”提升。 該應用必須啟動並帶有提升請求。

通常,如果應用程序通常不需要提升,則可以將需要提升的功能分解為由開關控制的模式,然后使用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目錄中,因此不需要提升。

在項目屬性中,將那些設置從Scope = Application更改為Scope = User。 這樣,它們就存儲在用戶的個人資料中,您不需要管理員特權即可對其進行修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM