首頁 > 後端開發 > C++ > 如何在運行時動態修改默認的app.config?

如何在運行時動態修改默認的app.config?

Mary-Kate Olsen
發布: 2025-01-25 17:28:11
原創
912 人瀏覽過

How to Dynamically Modify the Default app.config at Runtime?

執行階段動態修改預設 app.config

問題描述:

開發一個解決方案,能夠動態地將組態節從動態載入的應用程式模組載入到新的記憶體中app.config,確保應用程式透明地使用修改後的配置,而不會覆蓋預設的app. config。

解:

相關問題建議使用 SetData 方法變更配置系統路徑,但這僅在配置系統首次使用之前執行時有效。為了完全解決這個問題,還需要清除快取的配置值。

實作:

以下程式碼示範如何實現所需的行為:

<code class="language-csharp">using System;
using System.Configuration;
using System.Linq;
using System.Reflection;

public abstract class AppConfig : IDisposable
{
    public static AppConfig Change(string path)
    {
        return new ChangeAppConfig(path);
    }

    public abstract void Dispose();

    private class ChangeAppConfig : AppConfig
    {
        private readonly string oldConfig =
            AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();

        private bool disposedValue;

        public ChangeAppConfig(string path)
        {
            AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
            ResetConfigMechanism();
        }

        public override void Dispose()
        {
            if (!disposedValue)
            {
                AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig);
                ResetConfigMechanism();

                disposedValue = true;
            }
            GC.SuppressFinalize(this);
        }

        private static void ResetConfigMechanism()
        {
            typeof(ConfigurationManager)
                .GetField("s_initState", BindingFlags.NonPublic |
                                         BindingFlags.Static)
                .SetValue(null, 0);

            typeof(ConfigurationManager)
                .GetField("s_configSystem", BindingFlags.NonPublic |
                                            BindingFlags.Static)
                .SetValue(null, null);

            typeof(ConfigurationManager)
                .Assembly.GetTypes()
                .Where(x => x.FullName ==
                            "System.Configuration.ClientConfigPaths")
                .First()
                .GetField("s_current", BindingFlags.NonPublic |
                                       BindingFlags.Static)
                .SetValue(null, null);
        }
    }
}</code>
登入後複製

使用方法:

要暫時修改特定範圍的 app.config:

<code class="language-csharp">using (AppConfig.Change(tempFileName))
{
    // 应用程序使用修改后的 app.config
}</code>
登入後複製

要永久更改整個執行時間的 app.config:

<code class="language-csharp">// 应用程序使用修改后的 app.config
AppConfig.Change(tempFileName);</code>
登入後複製

以上是如何在運行時動態修改默認的app.config?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板