Donate

Cannot convert type 'System.Configuration.ConfigurationSection' to 'System.Collections.Specialized.NameValueCollection'

Good evening!
I've tried casting the config object to NameValueCollection using .NET Framework 4.5.2 of Visual Studio 2015 which I read from a tutorial on how to read config files using type NameValueSectionHandler. However, as I use the code below to cast the ConfigurationSection object to NameValueCollection,
C# Code
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollection scriptFiles = (NameValueCollection)config.GetSection("scriptfiles");
I get an error which is the title of this post. It seems that the code was applicable to older versions of .NET Framework and not the recent ones.
After doing some research, I found out that the workaround is to use ConfigurationManager.GetSection() in which the parameter passed is the SectionName of the config object instead of directly casting the ConfigurationSection object returned by the config.GetSection() method.
C# Code
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            
NameValueCollection scriptFiles = (NameValueCollection)ConfigurationManager.GetSection(config.GetSection("scriptfiles").SectionInformation.SectionName);            
Output
Cannot convert type 'System.Configuration.ConfigurationSection' to 'System.Collections.Specialized.NameValueCollection'
That's it!

Comments

Post a Comment

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input