我有一个带密码的数据库。 如果我允许使用connectionstring保存密码,那么它将在.config文件中显示。
如何在运行时设置相同的内容?
检查:
Point ADO.Net DataSet to different databases at runtime?
Changing dataset connection string at runtime
但是需要一些方法来更改连接字符串以设置自身以避免在许多位置进行更改。
更新:这是Windows窗体应用程序。
答案 0 :(得分:2)
这可以通过覆盖以下属性来实现。 步骤。
转到设置
点击查看代码
在视图代码中添加以下代码
Vb,Net
Default Public Overrides Property Item(ByVal propertyName As String) As Object
Get
If propertyName = "MyConnectionString" Then
Return MyBase.Item(propertyName) & ";Password=Yourpassword;"
End If
Return MyBase.Item(propertyName)
End Get
Set(ByVal value As Object)
MyBase.Item(propertyName) = value
End Set
End Property
C#(使用代码转换器转换的粗略代码)
public override object this[string propertyName] {
get {
if (propertyName == "MyConnectionString") {
return base.Item(propertyName) + ";Password=Yourpassword;";
}
return base.Item(propertyName);
}
set { base.Item(propertyName) = value; }
}
答案 1 :(得分:1)
使用DataSet
,我使用以下代码:
myDataSet myData = new myDataSet();
myDataSetTableAdapters.myTableAdapter myInfo =
new myDataSetTableAdapters.myTableAdapter();
myInfo.Connection.ConnectionString += ";Password=myPassword";
myInfo.Fill(myData.Info);
您可以自由设置tableAdapters ConnectionString的任何部分。
答案 2 :(得分:0)
功能性C#代码,刚刚测试过(基于@Sachin Chavan的精彩回答)。覆盖必须放在Settings.cs文件中:
public override object this[string propertyName]
{
get
{
if (propertyName == "nameOfYourConnectionStringProperty")
{
return base[propertyName].ToString().Replace("******", "Y0uRpA$sW0rD");
}
return base[propertyName];
}
set { base[propertyName] = value; }
}