将值引入app.config [英] introduce values into app.config
问题描述
您好
我有一个关于app.config的问题和c#
我在C#中有一个程序可以连接到sql并从我的数据库中获取一些信息。
我使用app.config连接到数据库,请按照以下代码:
< connectionStrings>
&NBSP; < add name =" sip" connectionString =" Data Source = JSALAZAR \ SQLEXPRESS; Initial Catalog = Sipelia; Integrated Security = True" providerName =" System.Data.SqlClient" />
< / connectionStrings>
但是,这是静态的。它将是相同的实例名称和数据库。我正在寻找一些根据实例名称和数据库名称引入动态数据的选项。
如果我需要连接,我如何使用一些字符串变量来引入不同的数据库和实例名称使用不同的服务器?
问候,
何塞
Hello Jose ,
>>如何使用一些字符串变量来引入不同的数据库和实例名称我需要与其他服务器联系吗?
您可以使用Configuration 类来实现它,它可以添加,删除,更新,在配置文件中选择节点信息。
public static void SettingConfig(string Serverinstance,string DatabaseName)
{
Configuration config = ConfigurationManager。 OpenExeConfiguration (ConfigurationUserLevel.None);
string ConnStr = string.Format(" Data Source = {0}; Initial Catalog = {1}; Integrated Security = True",Serverinstance,DatabaseName);
config.ConnectionStrings.ConnectionStrings [" sip"]。ConnectionString = ConnStr;
config.Save(ConfigurationSaveMode.Modified,true);
}
注意。您将在调试文件夹下的 .exe.config 文件中找到修改后的值。至于为什么不app app你可以看到
here 一>
Hello
I have a question about app.config and c#
I have a program in C# where I can connect to sql and get some information from my database.
I use app.config to connect into the database, please follow code below:
<connectionStrings>
<add name="sip" connectionString="Data Source=JSALAZAR\SQLEXPRESS;Initial Catalog=Sipelia;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
however, this is static. It will be the same instance name and database. I am looking some option to introduce dynamic data according to the instance name and database name.
How can I use some string variables to introduce a different database and instances name in case I need to conenct with a different server?
Regards,
Jose
Hello Jose,
>>How can I use some string variables to introduce a different database and instances name in case I need to conenct with a different server?
You could achieve it by using Configuration class ,which could add, remove, update, select node information in your config file.
public static void SettingConfig(string Serverinstance, string DatabaseName) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string ConnStr = string.Format("Data Source = {0}; Initial Catalog = {1}; Integrated Security = True", Serverinstance, DatabaseName); config.ConnectionStrings.ConnectionStrings["sip"].ConnectionString = ConnStr; config.Save(ConfigurationSaveMode.Modified, true); }
Note. you will find the modified value in your .exe.config file under debug folder . As for why not app config you could see here.
这篇关于将值引入app.config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!