У нас было редкое исключение происходит при чтении стандартных пользовательских настроек .Net (это те, найденные в «свойствах проекта» в VS 2008):C# - Настройки пользователя сломаны
System.Configuration.ConfigurationErrorsException was caught
Message="Configuration system failed to initialize"
Source="System.Configuration"
BareMessage="Configuration system failed to initialize"
Line=0
StackTrace:
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
at System.Diagnostics.DiagnosticsConfiguration.Initialize()
at System.Diagnostics.DiagnosticsConfiguration.get_IndentSize()
at System.Diagnostics.TraceInternal.InitializeSettings()
at System.Diagnostics.TraceInternal.get_Listeners()
InnerException: System.Configuration.ConfigurationErrorsException
Message="Unexpected end of file has occurred. The following elements are not closed: setting, SettingsTest.Properties.Settings, userSettings, configuration. Line 7, position 1. (C:\\Documents and Settings\\USER\\Local Settings\\Application Data\\Hitcents\\SettingsTest.vshost.exe_Url_ghwhc20utv4toanuinmj0pfsljthcugo\\1.0.0.0\\user.config line 7)"
Source="System.Configuration"
BareMessage="Unexpected end of file has occurred. The following elements are not closed: setting, SettingsTest.Properties.Settings, userSettings, configuration. Line 7, position 1."
Filename="C:\\Documents and Settings\\USER\\Local Settings\\Application Data\\Hitcents\\SettingsTest.vshost.exe_Url_ghwhc20utv4toanuinmj0pfsljthcugo\\1.0.0.0\\user.config"
Line=7
StackTrace:
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e)
InnerException: System.Xml.XmlException
Message="Unexpected end of file has occurred. The following elements are not closed: setting, SettingsTest.Properties.Settings, userSettings, configuration. Line 7, position 1."
Source="System.Xml"
LineNumber=7
LinePosition=1
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String arg)
at System.Xml.XmlTextReaderImpl.ThrowUnclosedElements()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlTextReaderImpl.Skip()
at System.Xml.XmlTextReader.Skip()
at System.Configuration.XmlUtil.StrictSkipToNextElement(ExceptionAction action)
at System.Configuration.BaseConfigurationRecord.ScanSectionsRecursive(XmlUtil xmlUtil, String parentConfigKey, Boolean inLocation, String locationSubPath, OverrideModeSetting overrideMode, Boolean skipInChildApps)
at System.Configuration.BaseConfigurationRecord.ScanSectionsRecursive(XmlUtil xmlUtil, String parentConfigKey, Boolean inLocation, String locationSubPath, OverrideModeSetting overrideMode, Boolean skipInChildApps)
at System.Configuration.BaseConfigurationRecord.ScanSections(XmlUtil xmlUtil)
at System.Configuration.BaseConfigurationRecord.InitConfigFromFile()
InnerException:
* Примечание: это воссоздан из тестового приложения.
Я остановил файл user.config, и половина его отсутствовала.
Я ожидаю, что наше заявление будет прекращено по какой-то причине.
Это, кажется, очень редко, вот как мы взаимодействуем с настройками:
//How we read
Settings settings = Settings.Default;
_ourStaticMemberVariable = settings.OurValue;
//How we save
Settings settings = Settings.Default;
settings.OurValue = "Our Value";
settings.Save();
Есть ли что-нибудь не так с тем, как мы используем его? Оба вызова имеют try-catch, которые помещают некоторые значения по умолчанию, но значения должны быть в состоянии сбросить с нашего приложения.
В этом состоянии наше приложение не может сохранять новые настройки - и я не могу найти хороший способ программно восстановить. Мне пришлось вручную найти user.config и удалить его.
Я также попытался вызвать Settings.Reset() и т. Д., Но получить то же исключение.
Любые идеи о том, как исправить это? Или нам лучше писать собственную систему настроек или сохранять постоянные настройки по-другому?
EDIT: Обходной путь заключается в удалении файла из кода, если вы получите исключение ConfigurationErrorsException.
Кто-нибудь знает, как получить полный путь к файлу user.config?
Как я могу получить путь к файлу настроек пользователя? База данных для моего сценария слишком сложна. – jonathanpeppers
Обратите внимание, что InnerException, типа System.Configuration.ConfigurationErrorsException, имеет свойство Filename ... – technophile
Я думаю, мне нужно будет создать вспомогательный метод, чтобы вытащить имя файла из внутреннего исключения. – jonathanpeppers