2016-12-03 6 views
1

実行時にconnectionstringを設定しようとしています。私が必要とするものは、実行時にdatasourceに設定し、アプリケーションを再起動します。私はグーグルで、いくつかのアプローチが見つかりましたが、問題は、私はsettings.csconnectionstringapp.configの両方を保存しようとしましたが、それは私のために動作しませんApplication.Restart();
app.configファイルでconnectionstringを操作する方法は?

後にデフォルト値にapp.config背中です。 は、これは私のコードです:

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は、デフォルト値

答えて

0

を持っているあなたはおそらくないだろう、それは動作しない場合がありますVSからこのコードをテスト(および場合)。

VSから実行すると実際に実行されるプログラムは<your_program>.vshost.exeで、対応する.configファイルの名前は<your_program>.vshost.exe.configとなり、そこで変更を確認する必要があります。

しかし...

VS変更を見ないように、元の.config.vshost.exe.configが同期に保ちます。コードの作品はVS外部からそれをしようか(Properties - >Debug)をEnabled the Visual Studio hosting processのチェックを外すかどうかをテストするために

(それはimplicationsを持っていることに注意してください)

enter image description here

+0

ありがとうございましたが、それは動作しません。 –

+0

@mohammadboluki私はそれを試してみました。魅力的な作品 –

関連する問題