Web.config配置文件的加密,解密及读写操作

代码都比较简单.不用多做说明:

ContractedBlock.gif ExpandedBlockStart.gif Code
aspx:
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="加密" OnClick="Button1_Click" />
&nbsp;&nbsp;
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="解密" /><br />
<br />
<asp:TextBox ID="txtConnectionStr" runat="server" Width="717px"></asp:TextBox><br />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="保存鏈接字串" />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="測試連線" /></div>
</form>
</body>

aspx.cs
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
Configuration config 
= WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section 
= config.Sections["connectionStrings"];
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(
"RsaProtectedConfigurationProvider");
section.SectionInformation.ForceSave 
= true;
config.Save(ConfigurationSaveMode.Modified);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Configuration config 
= WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section 
= config.ConnectionStrings;
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave 
= true;
config.Save(ConfigurationSaveMode.Modified);
}
}
protected void Button4_Click(object sender, EventArgs e)
{
string str = ConfigurationManager.ConnectionStrings["PEP"].ToString();
Response.Write(ConnectionTesting(str));
}
protected void Button3_Click(object sender, EventArgs e)
{
//測試數據庫鏈接字串是否正確.
if (ConnectionTesting(txtConnectionStr.Text) == "鏈接字串設置成功")
{
//保存當前鏈接字串到config
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection section 
= (ConnectionStringsSection)config.GetSection("connectionStrings");
section.ConnectionStrings[
"PEP"].ConnectionString = txtConnectionStr.Text;
config.Save(ConfigurationSaveMode.Modified);
}
}

protected string ConnectionTesting(string connstr)
{
string msg = "";
string str = string.IsNullOrEmpty(connstr) ? "" : connstr;
SqlConnection conn 
= new SqlConnection(str);
try
{
conn.Open();
msg 
= "鏈接字串設置成功";
}
catch (Exception ex)
{
msg 
= ex.Message.ToString();
}
finally
{
conn.Close();
}

return msg;
}

 

转载于:https://www.cnblogs.com/jimmyblog/archive/2008/08/18/1270570.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值