gpt4 book ai didi

c# - 尝试从 Windows 服务读取 IIS 站点的 web.config 文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:03 25 4
gpt4 key购买 nike

我正在尝试为安装在本地 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"); 抛出这个异常:

{"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"}

知道如何让它发挥作用吗?

最佳答案

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

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

关于c# - 尝试从 Windows 服务读取 IIS 站点的 web.config 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15825883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com