如何将更改后的值写回web.config?

时间:2016-11-16 06:09:41

标签: c# web-config

在我的web.config文件中,我有以下部分,

CREATE TABLE #Table1(Id INT, Name VARCHAR(100), Salary INT, DepartmentId INT)
CREATE TABLE #Table2(DID INT, DNAME VARCHAR(100))

INSERT INTO #Table1(Id , Name , Salary , DepartmentId )
SELECT 1,'Joe',70000,1 UNION ALL
SELECT 2,'Henry',80000,2 UNION ALL
SELECT 3,'Sam',60000,2 UNION ALL  
SELECT 4,'Max',90000,3 UNION ALL
SELECT 5,'Janet',69000,4 UNION ALL  
SELECT 6,'Randy',85000,1 

INSERT INTO #Table2(DID , DNAME)
SELECT 1,'IT' UNION ALL
SELECT 2,'ADMIN' UNION ALL
SELECT 3,'HR' UNION ALL
SELECT 4,'MARKETING' UNION ALL
SELECT 5,'SALES'  

;WITH CTE AS
(
 SELECT *,(SELECT COUNT(*) FROM #Table1 WHERE e.salary <= salary AND  departmentID=e.departmentID) AS RowNo FROM #Table1 e
)
SELECT * 
FROM 
( 
SELECT DNAME,salary,CASE WHEN RowNo = 1 THEN 'Best' WHEN RowNo  = 2 THEN 'Seond' WHEN RowNo = 3 THEN 'Best Worst' END RowNo
 FROM CTE 
 JOIN #Table2 ON DID = DepartmentId
 WHERE RowNo <= 3
 )A
PIVOT
(
  MAX(salary) FOR RowNo IN ([Best],[Seond],[Best Worst])
) PVT 

现在我需要更改stopProcessing的值并将其写回web.config。这就是我到目前为止所做的事情

<system.webServer>
    <rewrite>
      <rules>
        <rule name="rule 1D" stopProcessing="true">
          <match url="^(.*)$"  />
          <!--<action type="Rewrite" url="//offline.html"  />-->
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

但这种变化没有反映......

我在做什么错误?

完成 web.config

using System;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Xml.Linq;

namespace WebApplication3
{
    public partial class About : Page
    {        

        protected void btn1_Click(object sender, EventArgs e)
        {
            var configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");            
            var section = configuration.GetSection("system.webServer");
            var xdoc = XDocument.Load(new StringReader(section.SectionInformation.GetRawXml()));
            var dec = xdoc.Descendants("system.webServer");
            var stopProcessing = dec.Descendants("rules").SelectMany(i => i.Elements()).Select(s1 => s1.Attribute("stopProcessing")).Single().Value;
            stopProcessing = "false";
            configuration.Save();

        }
    }
}

1 个答案:

答案 0 :(得分:0)

重要提示:更改web.config文件会导致应用程序重启。

如果您的应用程序需要灵活的设置,那么您应该考虑使用其他方法...例如使用路由或自定义HttpHandler以及从XML文件或数据库读取/写入数据。

这对于使用配置文件可能会派上用场:

WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);
// "WebConfigurationManager" is located in the "System.Web.Configuration" namespace.