簡體   English   中英

如何更新web.config文件[asp.net]中的設置?

[英]How to update settings in web.config File [asp.net]?

如何在ASP.Net中的web.config文件中更新設置?

<appSettings>
  <add key="DataSource" value="localhost\SQLEXPRESS,1433">
  <add key="InitialCatalog" value="CenTimetracker" />
  <add key="user" value="uzer" /><add key="password" value="pazz" />
  <add key="IntegratedSecurity" value="True" />
  <add key="configured" value="False" />
</appSettings>

我正在開發一個ASP.NET網站,並使用web.config文件來保持數據庫連接詳細信息。 如上面的代碼段所示。

我正在使用以下代碼在運行時檢索保存的應用程序設置

string dataSource = ConfigurationManager.AppSettings["DataSource"].ToString();

如何將文本框中的值分配給web.config文件? 我已經使用了以下代碼,但是它不保存配置文件。

ConfigurationManager.AppSettings["DataSource"] = TextDataSource.Text;
Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
myConfiguration.AppSettings.Settings["DataSource"].Value = "some value";
myConfiguration.Save();

希望能幫助到你。

除了使用Configuration.Save()保存配置之外,您還需要注意文件許可權以保存文件。 您需要查看已使用哪個帳戶運行您的應用程序,然后將該帳戶的“修改/寫入”權限添加到web.config中。 如果允許匿名訪問,通常需要設置iusr_ [server]的權限。 在IIS中查找這些信息。

您也可以在嘗試使用該值的同一頁上加載其他值。 我在調試模式下使用類似的內容。 我之所以選擇此項,是因為上述方法會刪除與應用設置有關的所有注釋。

public string _path;
public string Path
{
    get
    {
        if(_path == null || _path == "")
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                _path = "localhost\SQLEXPRESS,1433";
            }
            else
            {
                _path = ConfigurationManager.AppSettings["DataSource"];
            }
            return _path;
        }
        return _path;
    }
}

@KeizerßloodŚucker:您可以按以下方式更改您的設置值:

    Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("path of webconfig file");
    myConfiguration.ConnectionStrings.ConnectionStrings["myDatabaseName"].ConnectionString = txtConnectionString.Text;
    myConfiguration.AppSettings.Settings.Add("key","value");
    myConfiguration.Save();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM