开发者

c# edit and update a web.config file from ASPX page

开发者 https://www.devze.com 2023-04-04 07:38 出处:网络
I have two keys in my web.config that I need to make available for editing in an ASPX page the keys are..

I have two keys in my web.config that I need to make available for editing in an ASPX page the keys are..

<add key="atlasuser" value="username" />
<add key="atlaspass" value="password" />

I have written this in the code behind for my ASPX Page

Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
string u_user = txtUsername.Text;
string u_pass = txtPassword.Text;

string crmSID = Request.QueryString["SID"];

config.AppSettings.Settings["atlasuser"].Value = u_user;
config.AppSettings.Settings["atlaspass"].Value = u_pass;

config.Save(ConfigurationSaveMode.Full);

When I edit the fields and click save I get an parse error message stating开发者_开发问答 that access to a .tmp file is denied and showing no relevant source lines in the source error box.

I am running windows 7 and I have checked that NETWORK SERVICE has full read write permissions to the directory.

Can anyone help me?


This msdn article seems to think you will want to define a null string to open the default config item.

http://msdn.microsoft.com/en-us/library/ms151456.aspx

If you do:

Configuration config = WebConfigurationManager.OpenWebConfiguration(null);

This should allow you to open the config to read/write, but as others have said this is not the best place to store this type of info


Check the config file is not set as read only?

PS - there is probably something wrong with your design if you are storing temporary information in the web config.


web.config cannot be edited from an ASP.NET application.

in theory .NET Framework provides the apis to edit/save changes in the app configuration files (which for ASP.NET applications is the web.config) but in practice in IIS this does not work because consider every single time the web.config is changed the IIS Application is restarted so .NET does not allow you saving to prevent this.

if you really need to allow changes in configuration from the ASPX pages you should either save in the database or in other external xml files then read those settings when needed.


You can edit the web.config file itself. Just make sure that the account you are running your application under has the appropriate file system permissions to be able to write to the application directory:

void editWebConfig(string key, string newValue, string filePath)
{
    var xml = new XmlDocument();
    xml.Load(filePath);
    using(FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
    {
        xml.SelectSingleNode("//configuration/appSettings/add[@key = '" + key + "']").Attributes["value"].Value = newValue;
        xml.Save(fs);
    }
}

Then you just call

editWebConfig("atlasuser", txtUsername.Text, Server.MapPath(".") + "\\web.config");
0

精彩评论

暂无评论...
验证码 换一张
取 消