2009-02-02 27 views
44

Wenn ich die Verbindungszeichenfolge mit diesem Code ändern, wird app.config zur Laufzeit nicht neu geladen. Ich habe erwartet, dass es ähnlich neu lädt wie wir app.config laden.Ändern Sie Verbindungszeichenfolge und laden Sie app.config zur Laufzeit

config.ConnectionStrings.ConnectionStrings["JVVNL_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString; 
config.ConnectionStrings.ConnectionStrings["CMS_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString; 
config.Save(ConfigurationSaveMode.Modified,true); 
ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.SectionName); 
+2

Bitte zu tun. Es ist sehr schwer zu lesen. – Cerebrus

Antwort

6

IIRC erfordert die ConfigurationManager.RefreshSection einen String-Parameter den Namen des Abschnitts Angabe zu aktualisieren:

ConfigurationManager.RefreshSection("connectionStrings"); 

Ich denke, dass die ASP.NET-Anwendung neu zu laden automatisch, wenn das Connection Element geändert wird und die Konfiguration muss nicht manuell neu geladen werden.

1

Ja, wenn ASP.NET web.config aktualisiert wird, wird die gesamte Anwendung neu gestartet, was bedeutet, dass die Datei web.config neu geladen wird.

2

Sie können die Konfiguration auch in seiner Gesamtheit aktualisieren:

ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName]; 

if (importToConnectionString == null) 
{ 
    importToConnectionString = new ConnectionStringSettings(); 
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString; 
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName; 
    importToConnectionString.Name = newName; 
    currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString); 
} 
else 
{ 
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString; 
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName; 
} 

Properties.Settings.Default.Reload(); 
+0

Hallo Neil, könntest du vielleicht deine Antwort erweitern? Ich bin ein Neuling. Wie setze ich currentConfiguration und importFromConnectionString? – robnardo

+0

@ neil-barnwell: Bitte unterstreichen Sie die Implementierung der Zeile "Properties.Settings.Default.Reload();". Gerade jetzt ist es zu kryptisch zu verstehen – dotnetguy

+0

@misrsud Nun, es tut, was es sagt - es lädt in den Speicher die Einstellungen, die Sie gerade in der Datei gespeichert haben. –

74

Haben genau dies zu tun. Dies ist der Code, der für mich gearbeitet:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings"); 
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah"; 
config.Save(); 
ConfigurationManager.RefreshSection("connectionStrings"); 
+0

@Bradley: Ich versuche das gleiche zu tun, aber ich bekomme UAC Rechte Probleme ... weil app.config in Programmdateien ist. Kann ich den Speicherort von app.config ändern? Ich habe 'AppDomain.CurrentDomain versucht.SetData ("APP_CONFIG_FILE", Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData) + "\\ app.config"); 'in' Main() 'aber es hat funktioniert. – prasy

+1

@Bradley Dies löst eine NullReferenceException für mich, also änderte ich es in 'config.ConnectionStrings.ConnectionStrings.Add (neue ConnectionStringSettings())', aber der Rest des Codes funktioniert. Vielen Dank! – knguyen

+0

@knguyen Klingt so, als hättest du entweder keinen Konfigurationsabschnitt namens "connectionStrings" oder keine Verbindungszeichenfolge, die in diesem Abschnitt definiert ist, mit dem Namen, den du in Zeile 3 (der ich "Blah" nannte) des Beispiels angegeben hast. –

1

Zuerst

using System.Configuration; 

Um die CS-Datei hinzufügen möchten. Wenn es nicht verfügbar ist, fügen Sie es über die Projektreferenzen hinzu, da es in einem neuen Projekt standardmäßig nicht enthalten ist.

Dies ist meine Lösung für dieses Problem. Zuerst habe ich die ConnectionProperties-Klasse erstellt, die die Elemente speichert, die ich in der ursprünglichen Verbindungszeichenfolge ändern muss. Die _name -Variable in der ConnectionProperties-Klasse ist wichtig, um der Name des connectionString zu sein. Die erste Methode nimmt eine Verbindungszeichenfolge und ändert die gewünschte Option mit dem neuen Wert.

private String changeConnStringItem(string connString,string option, string value) 
    { 
     String[] conItems = connString.Split(';'); 
     String result = ""; 
     foreach (String item in conItems) 
     { 
      if (item.StartsWith(option)) 
      { 
       result += option + "=" + value + ";"; 
      } 
      else 
      { 
       result += item + ";"; 
      } 
     } 
     return result; 
    } 

Sie können diese Methode ändern, um Ihre eigenen Bedürfnisse zu erfüllen. Ich habe sowohl mysql als auch mssql Verbindungen, also brauchte ich beide. Natürlich können Sie diesen Entwurfscode für sich selbst verfeinern.

Da ich keine trivialen Informationen hinzufügen wollte, habe ich die Properties-Region meines Codes weggelassen. Bitte fügen Sie es hinzu, wenn Sie möchten, dass dies funktioniert.

class ConnectionProperties 
{ 
    private String _name; 
    private String _dataSource; 
    private String _username; 
    private String _password; 
    private String _initCatalogue; 

    /// <summary> 
    /// Basic Connection Properties constructor 
    /// </summary> 
    public ConnectionProperties() 
    { 

    } 

    /// <summary> 
    /// Constructor with the needed settings 
    /// </summary> 
    /// <param name="name">The name identifier of the connection</param> 
    /// <param name="dataSource">The url where we connect</param> 
    /// <param name="username">Username for connection</param> 
    /// <param name="password">Password for connection</param> 
    /// <param name="initCat">Initial catalogue</param> 
    public ConnectionProperties(String name,String dataSource, String username, String password, String initCat) 
    { 
     _name = name; 
     _dataSource = dataSource; 
     _username = username; 
     _password = password; 
     _initCatalogue = initCat; 
    } 
// Enter corresponding Properties here for access to private variables 
} 
0

// hier ist, wie es in Windows App.Config korrekt Ihr Code-Snippet umformatieren

public static bool ChangeConnectionString(string Name, string value, string providerName, string AppName) 
    { 
     bool retVal = false; 
     try 
     { 

      string FILE_NAME = string.Concat(Application.StartupPath, "\\", AppName.Trim(), ".exe.Config"); //the application configuration file name 
      XmlTextReader reader = new XmlTextReader(FILE_NAME); 
      XmlDocument doc = new XmlDocument(); 
      doc.Load(reader); 
      reader.Close(); 
      string nodeRoute = string.Concat("connectionStrings/add"); 

      XmlNode cnnStr = null; 
      XmlElement root = doc.DocumentElement; 
      XmlNodeList Settings = root.SelectNodes(nodeRoute); 

      for (int i = 0; i < Settings.Count; i++) 
      { 
       cnnStr = Settings[i]; 
       if (cnnStr.Attributes["name"].Value.Equals(Name)) 
        break; 
       cnnStr = null; 
      } 

      cnnStr.Attributes["connectionString"].Value = value; 
      cnnStr.Attributes["providerName"].Value = providerName; 
      doc.Save(FILE_NAME); 
      retVal = true; 
     } 
     catch (Exception ex) 
     { 
      retVal = false; 
      //Handle the Exception as you like 
     } 
     return retVal; 
    } 
3
//You can apply the logic in "Program.cs" 

//Logic for getting new connection string 
//**** 
// 

MyDBName="mydb"; 

// 
//**** 

//Assign new connection string to a variable 
string newCnnStr = a="Data Source=.\SQLExpress;Initial Catalog=" + MyDBName + ";Persist Security Info=True;User ID=sa;Password=mypwd"; 

//And Finally replace the value of setting 
Properties.Settings.Default["Nameof_ConnectionString_inSettingFile"] = newCnnStr; 

//This method replaces the value at run time and also don't needs app.config for the same setting. It will have the va;ue till the application runs. 

//It worked for me. 
+0

Vielen Dank Kumpel –

+0

Was ist Eigenschaftenklasse? – abreneliere

Verwandte Themen