In my previous post about IIS, Virtual Directories and Directory Services you saw how can you obtain the sites per IIS instance as well sa all the root virtual directories. Now it is time to show you how can you obtain the Web.Config file for a root directory. At first glance I thought it will be easy, I thought I will simply need declare the following: using System.Web.Configuration; And / or : using System.Configuration; Well it's not quite this way. In order to load web.config file from a windows forms application you need to have some kind of context to be used or, in other words, file mapping. The following method takes two parameters : path to the root directory and DirectoryEntry, representing the root directory |
And here is the method:
List < string []> GetWebConfigAppSettings( string Path, DirectoryEntry entry)
{
List < string []> items = new List < string []>();
if (entry.Properties[ "Path" ].Value != null )
{
FileInfo fiWebConfig = new FileInfo (entry.Properties[ "Path" ].Value + @"\web.config" );
if (fiWebConfig.Exists)
{
WebConfigurationFileMap fm = new WebConfigurationFileMap ();
System.Collections. Hashtable props = new System.Collections. Hashtable ();
foreach (System.DirectoryServices. PropertyValueCollection property in entry.Properties)
{
string propertyName = property.PropertyName;
props.Add(propertyName, property.Value);
}
VirtualDirectoryMapping mapping = new VirtualDirectoryMapping (fiWebConfig.Directory.FullName, true );
fm.VirtualDirectories.Add(entry.Properties[ "AppRoot" ].Value.ToString(), mapping);
System.Configuration. Configuration cfg = System.Web.Configuration. WebConfigurationManager .OpenMappedWebConfiguration(fm, entry.Properties[ "AppRoot" ].Value.ToString());
foreach ( KeyValueConfigurationElement elmt in cfg.AppSettings.Settings)
{
items.Add( new string [] { elmt.Key, elmt.Value });
}
}
}
return items;
}
The method above will return a List
As you can see the magic begins in :
> System.Configuration. Configuration cfg = System.Web.Configuration. WebConfigurationManager .OpenMappedWebConfiguration(fm, entry.Properties[ "AppRoot" ].Value.ToString());
method. You simply need to make some preparations befor ask it to open the web.config.
Note : this code again is written in few minutes and does not pretend to be optimized, you can again use it at your own will.
No comments:
Post a Comment