Trying to read web.config file for an IIS site fro

2019-07-09 03:47发布

I am trying to look for a special web.config file for a web site installed on a local IIS. I do this search from a Windows service. I do the following:

using (ServerManager serverManager = new ServerManager())
{
    for (int r = 0; r < serverManager.Sites.Count; r++)
    {
        string strSiteName = serverManager.Sites[r].Name;
        ApplicationCollection arrApps = serverManager.Sites[r].Applications;

        for (int a = 0; a < arrApps.Count; a++)
        {
            Microsoft.Web.Administration.Application aa = arrApps[a];
            foreach (VirtualDirectory vd2 in aa.VirtualDirectories)
            {
                string strPhysPath = Environment.ExpandEnvironmentVariables(vd2.PhysicalPath);
                int rr = 0;

                try
                {
                    Configuration cnfg = serverManager.GetWebConfiguration(strSiteName, strPhysPath);
                    if (cnfg != null)
                    {
                        string swww = getWebConfigGeneralParamValue(cnfg, "SpecNodeName");
                    }
                }
                catch
                {
                    //Error
                }

            }
        }

    }

Where,

public static string getWebConfigGeneralParamValue(Configuration config, string strParamKey)
{
    string strRes = null;

    try
    {
        ConfigurationSection configSection1 = config.GetSection("configuration");
        if (configSection1 != null)
        {
            ConfigurationElement configGeneralParams = configSection1.GetChildElement("GeneralParams");
            if (configGeneralParams != null)
            {
                ConfigurationElementCollection configCol = configSection1.GetCollection();
                if (configCol != null)
                {
                    strRes = configCol[strParamKey].ToString();
                }
            }
        }
    }
    catch(Exception ex)
    {
        strRes = null;
    }

    return strRes;
}

and the web.config file that should be recognized by this script is something like this:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
 <!-- regular ASP.NET config stuff -->
 <GeneralParams>
  <param key="SpecNodeName" value="Special Node Value"/>
 </GeneralParams>
</configuration>

But what I get is that config.GetSection("configuration"); throws this exception:

{"Filename: \\?\C:\inetpub\wwwroot\C:\Users\Dev\Desktop\CSharp\MyTestWebApp\MyTestWebApp\web.config\r\nError: The configuration section 'configuration' cannot be read because it is missing a section declaration\r\n\r\n"}

Any idea how to make it work?

2条回答
疯言疯语
2楼-- · 2019-07-09 03:56

You need not to target configuration, you need to target that particular node from where you need to get your data. here is the example.

using(ServerManager mgr = ServerManager.OpenRemote("Some-Server")) {

  Configuration config = mgr.GetWebConfiguration("site-name", "/test-application");

  ConfigurationSection appSettingsSection = config.GetSection("appSettings");

  ConfigurationElementCollection appSettingsCollection = appSettingsSection.GetCollection();

  ConfigurationElement addElement = appSettingsCollection.CreateElement("add");
  addElement["key"] = @"NewSetting1";
  addElement["value"] = @"SomeValue";
  appSettingsCollection.Add(addElement);

  serverManager.CommitChanges();
} 
查看更多
Bombasti
3楼-- · 2019-07-09 04:10

I am feeling, if you have web.config why you want to use ServerManager. Take a look at below code, this I have been using in my code and it works as a charm. What it does is it loads web.config in readable format.

var assemblyPath = Path.GetDirectoryName(typeof (ConfigurationTests).Assembly.Location);
            string webConfigPath = MyPath;
            string directory = System.IO.Path.GetFullPath(Path.Combine(assemblyPath,webConfigPath));
            Console.WriteLine(directory);
            Assert.That(Directory.Exists(directory));

            VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(directory, true);
            WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
            wcfm.VirtualDirectories.Add("/", vdm);
            System.Configuration.Configuration webConfig = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");

            var connectionString = webConfig.ConnectionStrings.ConnectionStrings["ConnectionString"].ConnectionString;

            Console.WriteLine("Connection String:");
            Console.WriteLine(connectionString);


            Console.WriteLine("AppSettings:");
            foreach (var key in webConfig.AppSettings.Settings.AllKeys)
            {
                Console.WriteLine("{0} : {1}", key, webConfig.AppSettings.Settings[key].Value);
            }
查看更多
登录 后发表回答