簡體   English   中英

如何在app.config文件中操作connectionstring?

[英]how to manipulate connectionstring in app.config file?

我試圖在運行時設置connectionstring字符串。 我需要的是在運行時設置datasource並重啟應用程序。 我在谷歌找到了一些方法,但問題是app.configApplication.Restart();之后恢復到默認值Application.Restart();

我試圖在settings.csapp.config保存connectionstring ,但它對我不起作用。 這是我的代碼:

public void setConnectionString()
    {
        try
        {
            string str = string.Empty;

            str = string.Format(@"Data Source={0}; Initial Catalog=CRM01_DB; UID= {1}; PWD={2}", Default.DataSource, Default.UID, Default.UPass);

            this["CRM01_DBConnectionString"] = str;
            Default.Save();
            Thread.Sleep(100);
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
            connectionStringsSection.ConnectionStrings["CRM01_DBConnectionString"].ConnectionString = str;
            config.Save();
            ConfigurationManager.RefreshSection("connectionStrings");

            Thread.Sleep(100);

        }
        catch (System.Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }

我沒有得到任何錯誤,但是當應用程序啟動時, connectionstrig具有默認值

如果您從VS測試此代碼,它可能不起作用(可能不會)。

從VS運行時,實際執行的程序是<your_program>.vshost.exe ,相應的.config文件名為<your_program>.vshost.exe.config ,您應該檢查那里的更改。

但..

VS保持原始.config.vshost.exe.config同步,以便您看不到您的更改。

要測試代碼是否有效,請從VS外部嘗試或取消選中Enabled the Visual Studio hosting processProperties - > Debug )(請記住它有影響

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM