C#修改库中存在的连接字符串
我有一个类库,里面只有一个DataSet(MySQL连接器)和一个Connector类。
我在多个项目中使用此类连接到数据库,我总是在连接字符串中嵌入密码,但现在我需要能够修改此字符串(出于安全目的),所以我可以让用户使用自己的连接帐户。
如何修改此连接字符串。
我尝试了以下内容
Properties.Settings.Default.DataBaseConnectionString = "String";
但似乎连接字符串是readonly因为它似乎没有setter值。
我也试过以下没有运气
Properties.Settings.Default.DatabaseConnectionString.Insert( Properties.Settings.Default.DatabaseConnectionConnectionString.Length - 1, "Password=dbpassword;");
您可以像这样修改它们:
Properties.Settings.Default["MyConnectionString"] = newCnnStr;
对于也将新值保存到文件的完整解决方案,您需要执行以下操作:
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; }
如果您的数据集位于另一个程序集中,您仍然可以执行此操作,前提是您公开该程序集的设置。 去做这个:
- 右键单击解决方案资源管理器中的项目,然后单击“ 属性”
- 单击“ 设置”选项卡。
- 将Access Modifier下拉列表更改为“Public”,保存并关闭。
然后你可以这样做(假设另一个项目叫做“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; }
你不是那个类的源代码吗?
此外,但更复杂的方法是使用Reflex和Reflexil AddIn 修补程序集 。
我想您正在询问如何在运行时更改连接字符串属性,具体取决于谁在使用该应用程序。 希望这可以帮助。
在过去,我通过使我的连接字符串包含我可以使用string.Format提供的参数来完成此操作。
string connectionString = string.Format(ConfigurationManager.ConnectionStrings["SomeDB"].ConnectionString, location, password);
看起来您正在从配置文件加载连接字符串,您应该能够从那里更改它。 一旦构建,它将是一个名为与编译forms相同的文件加上.config。 (例如application.exe.config)