2015-06-18 5 views
1

Я пытался следуя инструкции app.config Custom Configurationapp.config пользовательские настройки - 'System.TypeInitializationException'

Однако, я застрял. Это мой app.config код:

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
    <section name="Configuration" type="DP.Configuration, MyAssembly" /> 
    </configSections> 
    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/> 
    </startup> 
    <Configuration 
     inputLoc="C:\Input" 
    /> 
</configuration> 

здесь класс конфигурации:

using System.Configuration; 

    namespace DP 
    { 
     public class Configuration : ConfigurationSection 
     { 
      private static readonly Configuration settings = ConfigurationManager.GetSection("Configuration") as Configuration; 

     public static Configuration Settings 
     { 
      get 
      { 
       return settings; 
      } 
     } 

     [ConfigurationProperty("inputLoc", IsRequired = true)] 
     [StringValidator(InvalidCharacters = " [email protected]#$%^&*()[]{}/;’\"|", MinLength = 1, MaxLength = 256)] 
     public string InputLocation 
     { 
      get { return (string)this["inputLoc"]; } 
      set { this["inputLoc"] = value; } 
     } 
    } 
} 

И когда я называю inputFolder = ClientConfiguration.Settings.InputLocation; я получаю System.TypeInitializationException.

Код ошибки:

An unhandled exception of type 'System.TypeInitializationException' occurred in DP.exe 

Additional information: The type initializer for 'DP.configuration' threw an exception. 

System.TypeInitializationException was unhandled 
    _HResult=-2146233036 
    _message=The type initializer for 'DP.Configuration' threw an exception. 
    HResult=-2146233036 
    IsTransient=false 
    Message=The type initializer for 'DP.Configuration' threw an exception. 
    Source=DP 
    TypeName=DP.Configuration 
    StackTrace: 
     at DP.Configuration.get_Settings() 
     at DP.Program.Main(String[] args) in c:\Program.cs:line 1012 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: System.Configuration.ConfigurationErrorsException 
     _HResult=-2146232062 
     _message=An error occurred creating the configuration section handler for Configuration: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. 
     HResult=-2146232062 
     IsTransient=false 
     Message=An error occurred creating the configuration section handler for Configuration: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. (C:\DP.vshost.exe.Config line 4) 
     Source=System.Configuration 
     BareMessage=An error occurred creating the configuration section handler for Configuration: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. 
     Filename=C:\DP.vshost.exe.Config 
     Line=4 
     StackTrace: 
      at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere) 
      at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) 
      at System.Configuration.BaseConfigurationRecord.GetSection(String configKey) 
      at System.Configuration.ConfigurationManager.GetSection(String sectionName) 
      at DP.Configuration..cctor() in c:\\Configuration.cs:line 7 
     InnerException: System.IO.FileNotFoundException 
      _HResult=-2147024894 
      _message=Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. 
      HResult=-2147024894 
      IsTransient=false 
      Message=Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. 
      Source=System.Configuration 
      FileName=MyAssembly 
      FusionLog==== Pre-bind state information === 
LOG: DisplayName = MyAssembly 
(Partial) 
WRN: Partial binding information was supplied for an assembly: 
WRN: Assembly Name: MyAssembly | Domain ID: 1 
WRN: A partial bind occurs when only part of the assembly display name is provided. 
WRN: This might result in the binder loading an incorrect assembly. 
WRN: It is recommended to provide a fully specified textual identity for the assembly, 
WRN: that consists of the simple name, version, culture, and public key token. 
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue. 
LOG: Appbase = file:///C://x64/Debug/ 
LOG: Initial PrivatePath = NULL 
Calling assembly : System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. 
=== 
LOG: This bind starts in default load context. 
LOG: Using application configuration file: C:\DP.vshost.exe.Config 
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config. 
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). 
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly.DLL. 
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly/MyAssembly.DLL. 
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly.EXE. 
LOG: Attempting download of new URL file:///C://x64/Debug/MyAssembly/MyAssembly.EXE. 

      StackTrace: 
       at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError) 
       at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) 
       at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord) 
       at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord) 
       at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere) 
      InnerException: 
+0

Существует ли 'C: \ Input' в файловой системе? –

+0

вы должны объявить элемент. –

+1

Всякий раз, когда вы публикуете об исключении, разместите полное исключение. Только для устранения неполадок поставьте блок try/catch вокруг кода, вызывающего исключение. В блоке catch отобразите 'ex.ToString()' и опубликуйте результат в своем вопросе. –

ответ

1

Смотрите этот вопрос: configurationsection-stringvalidator-failing

Похоже, что вам нужно добавить атрибут значения по умолчанию в атрибуте ConfigurationProperty, то есть.

[ConfigurationProperty("inputLoc", IsRequired = true, DefaultValue="something")] 
+0

Я пробовал это, но он не сделал спокойный работа. – lynx

+0

Он работает для меня в решении проблемы, связанной с исключением инициализатора типа StringValidator. –

0

Вместо ... inputFolder = ClientConfiguration.Settings.InputLocation;

Попробуйте это ... inputFolder = Configuration.Settings.InputLocation;

+0

Извините, у меня это как inputFolder = Configuration.Settings.InputLocation; я обновил код, вставленный неправильно – lynx

0

В основном, я вставлял неправильное имя сборки. Я исправил это, положив в c

Смежные вопросы