代码之家  ›  专栏  ›  技术社区  ›  Wilhelm

如何通过c#Windows窗体应用程序读取和更新外部web.config

  •  0
  • Wilhelm  · 技术社区  · 7 年前

    我正在构建一个c#Windows应用程序来维护一个WEB应用程序——特别是在WEB.config文件中创建和更新值。我在这里尝试了很多建议,但它们都只是描述如何从应用程序内部读取和写入配置文件。web.config的一部分:

    - 
     <configuration>
        <system.web>
            <customErrors mode="Off"/>
    
            <compilation debug="true" targetFramework="4.0" />
            <globalization culture="" enableClientBasedCulture="true" uiCulture="" />
    
            <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
        </system.web>
        <appSettings>
            <add key="DocPath" value="~/serverdocs/docs" />
    
            <add key="TextForLabel1" value="This is some text"/>
    ..
    

        var xmlDoc = new XmlDocument();
            xmlDoc.Load(FName); // name and path from web.config file
    

    然后读取所有节点,如:

                foreach (XmlNodeList xmlnodes in xmlDoc.SelectNodes("configuration/appSettings"))
                {
                    foreach ( XmlNode node in xmlnodes)
                    {
                    string MyKey = node.Name;
                    string MyVal = node.Value;
                    }
    
                }  
    

    无法将类型为“System.Xml.XmlDeclaration”的对象转换为类型为“System.Xml.XmlNodeList”。或者,根据我如何写入select值,无法找到项目。

    有时候,我可能是在盲目阅读自己的代码并检测到错误-对不起-欢迎任何建议。

    3 回复  |  直到 7 年前
        1
  •  1
  •   Martin Joseph Silber    7 年前

    XmlDocument .

    相反,您实际上可以使用 WebConfigurationManager

    Configuration cfg = WebConfigurationManager.OpenWebConfiguration("YOUR_WEB_CONFIG");
    

    一旦您在 Configuration 对象,则可以枚举配置文件的节和值。

    您将需要添加对这两个对象的引用 System.Configuration System.Web 为了利用上述信息。

    威廉发表评论说他无法打开 web.config this answer )可用于加载文件:

    public static Configuration OpenConfigFile(string configPath)
    {
        var configFile = new FileInfo(configPath);
        var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
        var wcfm = new WebConfigurationFileMap();
        wcfm.VirtualDirectories.Add("/", vdm);
        return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
    }
    

    使用:

    Configuration cfg = OpenConfigFile(@"YOUR_WEB_CONFIG");
    
        2
  •  0
  •   Wilhelm    7 年前

       var xmlDoc = new XmlDocument();
        xmlDoc.Load(FName);
        DataTable DTConfig = new DataTable();
        DTConfig.Columns.Add("Key", typeof(string));
        DTConfig.Columns.Add("Value", typeof(string));
        DTConfig.Columns.Add("OldValue", typeof(string));
        try
        {
            foreach (XmlElement xmlElement in xmlDoc.SelectNodes("configuration/appSettings"))
            {
                foreach (XmlNode node in xmlElement)
                {
                    if (node.Attributes != null && node.Attributes.Count > 1)
                    {
                        string MyKey = "";
                        string MyVal = "";
                        if (node.Attributes[0].Value != null)
                        {
                            MyKey = node.Attributes[0].Value;
                        }
                        if (node.Attributes[1].Value != null)
                        {
                            MyVal = node.Attributes[1].Value;
                        }
                        DataRow DR = DTConfig.NewRow();
                        DR["Key"] = MyKey;
                        DR["Value"] = MyVal;
                        DR["OldValue"] = MyVal;
                        if (MyKey != "")
                        {
                            DTConfig.Rows.Add(DR);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Debug.Print(ex.Message);
        }
        TxtFname.Text = FName;
        DGConfig.DataSource = DTConfig;
        return true;
    

        3
  •  -1
  •   ggariepy    7 年前

    我遇到了一个类似的问题,并且走了与您相同的道路,尝试遍历XML树以找到需要更改的节点。它是一个键/值对,为web服务连接定义了URI。指向本地主机的默认URI,例如:

        <add key="ProcessorService" value="https://localhost/Processor/ProcessorService.asmx" />
    

    (Get-Content $webConfig -Encoding UTF8) | `
        ForEach-Object {$_ -replace 'localhost', "$dnsName" } | `
        Set-Content $webConfig
    

    我在一个循环中运行了上述内容,该循环遍历了每个目录中的每个web.config文件,进行了修改,然后使用Set-Content cmdlet保存了该文件。

    如果你愿意,我可以理解

    我就我个人而言,我讨厌使用XML,除非我被迫这样做。您当然可以这样做,但如果有人出现并重新排列您的web.config文件,他们将破坏您精心制作的XML walker,您将从头开始。这样,只要你正在改变的东西没有改变(太多),它就可以正常工作。