Проблема с публикацией файла user.config в .NET 5.0.

Я пытаюсь перенести проект WPF с.NET Core 3.1 на.NET 5.0. В моем проекте используется файл свойств по умолчанию (user.config) для хранения некоторых данных приложения.

Код проекта:

       
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            try
            {
                Properties.Settings.Default.test = "Edited";
                Properties.Settings.Default.Save();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
    }

После публикации проекта я получаю System.IO.FileNotFoundException (указанный файл не может быть найден) при попытке доступа к Properties.Settings.Default.

       ---------------------------

---------------------------
System.IO.FileNotFoundException: Не удается найти указанный файл. (0x80070002)

   at System.Reflection.RuntimeModule.GetFullyQualifiedName()

   at System.Reflection.RuntimeModule.get_Name()

   at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)

   at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)

   at System.Configuration.Internal.ConfigurationManagerInternal.System.Configuration.Internal.IConfigurationManagerInternal.get_ExeProductName()

   at System.Configuration.ApplicationSettingsBase.get_Initializer()

   at System.Configuration.ApplicationSettingsBase.CreateSetting(PropertyInfo propertyInfo)

   at System.Configuration.ApplicationSettingsBase.EnsureInitialized()

   at System.Configuration.ApplicationSettingsBase.get_Properties()

   at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)

   at System.Configuration.SettingsBase.get_Item(String propertyName)

   at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)

   at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)

   at WpfApp1.Properties.Settings.get_test()

   at WpfApp1.MainWindow..ctor()
---------------------------
ОК   
---------------------------

Проблема возникает только при использовании публикации в один файл.

Мои свойства публикации:

       <?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121. 
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration>Release</Configuration>
    <Platform>Any CPU</Platform>
    <PublishDir>bin\Release\net5.0\publish\</PublishDir>
    <PublishProtocol>FileSystem</PublishProtocol>
    <TargetFramework>net5.0-windows</TargetFramework>
    <RuntimeIdentifier>win-x86</RuntimeIdentifier>
    <SelfContained>true</SelfContained>
    <PublishSingleFile>True</PublishSingleFile>
    <PublishReadyToRun>True</PublishReadyToRun>
    <PublishTrimmed>False</PublishTrimmed>
    <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
  </PropertyGroup>
</Project>

Класс настроек:

           [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
        
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
        
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("123")]
        public string test {
            get {
                return ((string)(this["test"]));
            }
            set {
                this["test"] = value;
            }
        }
    }

Файл проекта:

       <Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
    <TargetPlatformIdentifier>Windows</TargetPlatformIdentifier>
  </PropertyGroup>

  <ItemGroup>
    <Compile Update="Properties\Settings.Designer.cs">
      <DesignTimeSharedInput>True</DesignTimeSharedInput>
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
    </Compile>
  </ItemGroup>

  <ItemGroup>
    <None Update="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
  </ItemGroup>

</Project>

Примечание 1. Я проверил папку%userprofile%\appdata\local, и она не создает файл user.config после запуска приложения.

Примечание 2: если я помещаю mscorrc.dll в папку публикации, все работает нормально.

1 ответ

Похоже, есть ошибка в обработке.NET 5 устаревших настроек при использовании публикации в один файл. Связанная проблема Github показывает, что попытка прочитать любой параметр, а не только настройки пользователя, приводит к System.IO.FileNotFoundException. Исправление этого не было включено в.NET 5.0.

Из выпуска:

Обходной путь - установить <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>

В долгосрочной перспективе вам все равно придется перейти на систему конфигурации.NET Core. app.config и user.config являются устаревшими технологиями, и подобных проблем следует ожидать.

Другие вопросы по тегам