.NET 5 WinForms 应用程序中的设置保存在哪里?

Where are the settings saved in a .NET 5 WinForms app?

在 .NET Framework WinForms 项目中,项目中有一个 App.config 文件,它是一个 XML 文件,其中包含一个引用 class 的 configSection System.Configuration,以及用户设置本身的部分,如下所示:

<configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561944e089">
        <section name="MyAppName.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561944e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
</configSections>
<userSettings>
    <MyAppName.Properties.Settings>
        <setting name="Test" serializeAs="String">
            <value>Some Value</value>
        </setting>
    </MyAppName.Properties.Settings>
</userSettings>

这在构建文件夹中创建了一个文件,其应用程序名称加上 .exe.config,如 MyAppName.exe.config.

但是当我使用 .NET 创建一个新的 WinForms 项目时:

解决方案中没有App.config。我可以使用项目属性编辑设置:

我可以访问这些值,并使用相同的 Properties 对象和方法更新它们:

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            textBox1.Text = Properties.Settings.Default.Test;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.Test = textBox1.Text;

            Properties.Settings.Default.Save();
        }
    }
}

一切似乎都正常,但是当我检查 bin 文件夹时,我看不到实际存储值的文件。

如果 .NET 5 保存的应用程序设置不在与应用程序的 exe 相同的文件夹中的文件中?

用户设置存储在以下路径的user.config文件中:

%userprofile%\appdata\local\<Application name>\<Application uri hash>\<Application version>

Application settings 文件默认情况下不会创建(意外),但是如果您在应用程序的 dll/exe 文件旁边手动创建它们,配置系统将根据它。文件名应为 <Application name>.dll.config。注意文件扩展名 .dll.config.

你可能想看看下面类的源代码:

在撰写此答案时 Application Settings for Windows Forms 仍然没有任何 .NET 5 的条目并重定向到 4.x 文档。

首先,这是一个(.NET 团队)已知问题:https://github.com/dotnet/project-system/issues/7772

其次,问题和解决方案在您的问题中得到了很好的描述:

(before) ..there was an App.config file in the project,.. (now) There is no App.config in the solution...

添加缺少的 app.config,一切都会像以前一样工作。