首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >System.Configuration始终保存默认值

System.Configuration始终保存默认值
EN

Stack Overflow用户
提问于 2021-02-23 20:05:27
回答 1查看 34关注 0票数 0

对于我的项目,我需要一个配置,它是存储在同一个文件夹中的可执行文件,可以很容易地访问和编辑的用户。我在下面的文章中找到了这个问题的解决方案System.Configuration包,但现在我遇到了一个问题。问题是,当我尝试保存配置文件时,它会创建该文件,但会使用我认为是默认值的值填充所有值(因此,如果字符串为空,则为空Black对于ConsoleColor)

为了保存并在以后检查配置,我使用以下代码:

代码语言:javascript
复制
static void Main()
{
        #if DEBUG
            string applicationName =
                Environment.GetCommandLineArgs()[0];
        #else
            string applicationName =
            Environment.GetCommandLineArgs()[0]+ ".exe";
        #endif

            string exePath = System.IO.Path.Combine(
                Environment.CurrentDirectory, applicationName);

            // Get the configuration file. The file name has
            // this format appname.exe.config.
            System.Configuration.Configuration config =
              ConfigurationManager.OpenExeConfiguration(exePath);

            try
            {

                // Create the custom section entry  
                // in  group and the 
                // related target section in .
                if (config.Sections["CustomSection"] == null)
                {
                    ConsoleSection customSection = new ConsoleSection();
                    customSection.BackgroundColor = "Black";
                    customSection.ForegroundColor = "White";

                    config.Sections.Add("CustomSection", customSection);

                    // Save the configuration file.
                    customSection.SectionInformation.ForceSave = true;
                    config.Save(ConfigurationSaveMode.Full);

                    Console.WriteLine("Created configuration file: {0}",
                        config.FilePath);
                }
            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine("CreateConfigurationFile: {0}", err.ToString());
            }

            // Display feedback.
            Console.WriteLine();
            Console.WriteLine("Using OpenExeConfiguration(string).");
            // Display the current configuration file path.
            Console.WriteLine("Configuration file is: {0}",
              config.FilePath);

            ConsoleSection sect = config.GetSection("CustomSection") as ConsoleSection;

            Console.WriteLine("FG Color: {0}",
              sect.ForegroundColor);
            Console.WriteLine("BG Color: {0}",
              sect.BackgroundColor);

            return;
}

和ConsoleSection类:

代码语言:javascript
复制
public class ConsoleSection : ConfigurationSection
{
    public ConsoleSection()
    {
    }

    [ConfigurationProperty("BackgroundColor", IsRequired=true)]
    public string BackgroundColor {
        get { return (string)(this["BackgroundColor"]); }
        set { this["BackgroundColor"] = value; } 
    }

    [ConfigurationProperty("ForegroundColor", IsRequired = true)]
    public string ForegroundColor
    {
        get { return (string)(this["ForegroundColor"]); }
        set { this["ForegroundColor"] = value; }
    }
}

我还注意到,在第一次运行期间(当它应该保存内容时),它可以很好地读取值,所以如果您要保存这段代码并运行它,第一次运行将产生预期的输出。

这段代码的目标是.NET核心3.1,如果这很重要的话。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-23 20:48:10

导致此错误的原因有两点。

  1. 缺少更新部分意味着您已经编写了仅用于添加新配置节的代码。什么是CustomSection已经存在了吗?
  2. 您需要在更新配置后刷新该部分。

请看下面的代码。如果它在所有测试用例中都能正常工作。

代码语言:javascript
复制
void Main()
{
    #if DEBUG
        string applicationName = Environment.GetCommandLineArgs()[0];
    #else
        string applicationName = Environment.GetCommandLineArgs()[0] + ".exe";
    #endif

    string exePath = System.IO.Path.Combine(Environment.CurrentDirectory, applicationName);

    // Get the configuration file. The file name has
    // this format appname.exe.config.
    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"E:\Temp\TwitterBot\TwitterBot\bin\Debug\TwitterBot.exe");

    try
    {

        // Create the custom section entry
        // in  group and the
        // related target section in .
        if (config.Sections["CustomSection"] == null)
        {
            ConsoleSection customSection = new ConsoleSection();
            customSection.BackgroundColor = "Black";
            customSection.ForegroundColor = "White";

            config.Sections.Add("CustomSection", customSection);

            // Save the configuration file.
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Modified);

            Console.WriteLine("Created configuration file: {0}", config.FilePath);
        }
        //Missing Else Part
        else
        {
            config.Sections.Remove("CustomSection");

            ConsoleSection customSection = new ConsoleSection();
            customSection.BackgroundColor = "Red";
            customSection.ForegroundColor = "Pink";

            config.Sections.Add("CustomSection", customSection);
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Modified);
        }
    }
    catch (ConfigurationErrorsException err)
    {
        Console.WriteLine("CreateConfigurationFile: {0}", err.ToString());
    }

    //After updating the values you need to refresh the section before reading it.
    ConfigurationManager.RefreshSection("CustomSection");

    // Display feedback.
    Console.WriteLine();
    Console.WriteLine("Using OpenExeConfiguration(string).");
    // Display the current configuration file path.
    Console.WriteLine("Configuration file is: {0}", config.FilePath);

    ConsoleSection sect = config.GetSection("CustomSection") as ConsoleSection;

    Console.WriteLine("FG Color: {0}", sect.ForegroundColor);
    Console.WriteLine("BG Color: {0}", sect.BackgroundColor);

    return;
}

public class ConsoleSection : ConfigurationSection
{
    public ConsoleSection()
    {
    }

    [ConfigurationProperty("BackgroundColor", IsRequired = true)]
    public string BackgroundColor
    {
        get { return (string)(this["BackgroundColor"]); }
        set { this["BackgroundColor"] = value; }
    }

    [ConfigurationProperty("ForegroundColor", IsRequired = true)]
    public string ForegroundColor
    {
        get { return (string)(this["ForegroundColor"]); }
        set { this["ForegroundColor"] = value; }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66332801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档