Mic*_*han 1 c# wpf settings connection-string database-connection
我有一个类库,里面只有一个DataSet(MySQL连接器)和一个Connector类.
我在多个项目中使用此类连接到数据库,并且我总是将密码嵌入到连接字符串中,但现在我需要能够修改此字符串(出于安全目的),因此我可以让用户使用自己的连接帐户.
如何修改此连接字符串.
我尝试了以下内容
Properties.Settings.Default.DataBaseConnectionString = "String";
Run Code Online (Sandbox Code Playgroud)
但似乎连接字符串是readonly因为它似乎没有setter值.
我也试过以下没有运气
Properties.Settings.Default.DatabaseConnectionString.Insert(
Properties.Settings.Default.DatabaseConnectionConnectionString.Length - 1,
"Password=dbpassword;");
Run Code Online (Sandbox Code Playgroud)
您可以像这样修改它们:
Properties.Settings.Default["MyConnectionString"] = newCnnStr;
Run Code Online (Sandbox Code Playgroud)
对于也将新值保存到文件的完整解决方案,您需要执行以下操作:
private static void ModifyConnectionStrings()
{
// Change the value in the config file first
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
const string newCnnStr = "server=(local);database=MyDb;user id=user;password=secret";
config.ConnectionStrings.ConnectionStrings["MyProject.Properties.Settings.MyConnectionString"].ConnectionString = newCnnStr;
config.Save(ConfigurationSaveMode.Modified, true);
// Now edit the in-memory values to match
Properties.Settings.Default["MyConnectionString"] = newCnnStr;
}
Run Code Online (Sandbox Code Playgroud)
如果您的数据集位于另一个程序集中,您仍然可以执行此操作,前提是您公开该程序集的设置.去做这个:
然后你可以这样做(假设另一个项目被称为"MyProject.DataLayer"):
private static void ModifyConnectionStrings()
{
// Change the value in the config file first
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
const string newCnnStr = "server=(local);database=MyDb;user id=user;password=secret";
config.ConnectionStrings.ConnectionStrings["MyProject.Properties.Settings.MyConnectionString"].ConnectionString = newCnnStr;
config.ConnectionStrings.ConnectionStrings["MyProject.DataLayer.Properties.Settings.MyConnectionString"].ConnectionString = newCnnStr;
config.Save(ConfigurationSaveMode.Modified, true);
// Now edit the in-memory values to match
Properties.Settings.Default["MyConnectionString"] = newCnnStr;
MyProject.DataLayer.Properties.Settings.Default["MyConnectionString"] = newCnnStr;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6083 次 |
| 最近记录: |