【问题标题】:Trying to read web.config file for an IIS site from a Windows service尝试从 Windows 服务读取 IIS 站点的 web.config 文件
【发布时间】:2013-03-27 09:26:51
【问题描述】:

我正在尝试为安装在本地 IIS 上的网站寻找特殊的 web.config 文件。我从 Windows 服务进行此搜索。我执行以下操作:

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
                }

            }
        }

    }

在哪里,

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;
}

这个脚本应该能识别的 web.config 文件是这样的:

<?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>

但我得到的是config.GetSection("configuration"); 抛出了这个异常:

{"文件名: \\?\C:\inetpub\wwwroot\C:\Users\Dev\Desktop\CSharp\MyTestWebApp\MyTestWebApp\web.config\r\n错误: 无法读取配置部分“配置”,因为它是 缺少部分声明\r\n\r\n"}

知道如何让它工作吗?

【问题讨论】:

    标签: c# asp.net iis service web-config


    【解决方案1】:

    您不需要针对配置,您需要针对需要从中获取数据的特定节点。这是一个例子。

    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();
    } 
    

    【讨论】:

    • 谢谢。现在更正GetWebConfiguration 中的路径后,我仍然遇到异常:The configuration section 'configuration' cannot be read because it is missing a section declaration
    【解决方案2】:

    我觉得,如果你有 web.config,为什么要使用 ServerManager。 看看下面的代码,我一直在我的代码中使用它,它就像一个魅力。 它的作用是以可读格式加载 web.config。

    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);
                }
    

    【讨论】:

    • 谢谢。我最终只是使用XmlTextReader 解析了 web.config。写起来要花一点时间,但至少你知道发生了什么,这与所有那些内置的解析类非常混淆。
    猜你喜欢
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多