2008-09-15 11 views
9

Möchten Sie die Verbindungszeichenfolge für eine Datenbank, die den Mitgliedschaftsanbieter von asp.net in einer Windows-Anwendung verwendet, programmgesteuert ändern. Der Namespace system.configuration erlaubt Änderungen an den Benutzereinstellungen, jedoch möchten wir eine Anwendungseinstellung anpassen? Muss man eine Klasse schreiben, die XML verwendet, um die Klasse zu modifizieren? Muss man die aktuellen Verbindungen löschen (kann man eine Verbindung zum Löschen auswählen) und eine neue hinzufügen? Kann man den bestehenden Verbindungsstring anpassen?VS2005 C# Programmatische Änderung der Verbindungszeichenfolge in app.config

Antwort

6

Sie programmatisch die Konfiguration mit der Verwendung des System.Configuration Namensraum öffnen:

Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

Dann können Sie Zugriff auf die Verbindungszeichensammlung an:

myConfig.ConnectionStrings.ConnectionStrings

Sie ändern die Sammlung, aber wie Sie wollen, und wenn Sie fertig sind, rufen Sie .Save() auf dem Konfigurationsobjekt.

0

Verwenden Sie die ConnectionStringsSection-Klasse. Die Dokumentation bietet sogar ein Beispiel, wie man einen neuen ConnectionString erstellt und das Framework in der Konfigurationsdatei speichert, ohne den gesamten XML-Shebang implementieren zu müssen.

Siehe here und suchen Sie nach einem Beispiel.

8
// Get the application configuration file. 
System.Configuration.Configuration config = 
     ConfigurationManager.OpenExeConfiguration(
     ConfigurationUserLevel.None); 

// Create a connection string element and 
// save it to the configuration file. 

// Create a connection string element. 
ConnectionStringSettings csSettings = 
     new ConnectionStringSettings("My Connection", 
     "LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" + 
     "Initial Catalog=aspnetdb", "System.Data.SqlClient"); 

// Get the connection strings section. 
ConnectionStringsSection csSection = 
    config.ConnectionStrings; 

// Add the new element. 
csSection.ConnectionStrings.Add(csSettings); 

// Save the configuration file. 
config.Save(ConfigurationSaveMode.Modified); 
+0

Dies ist eine Verbindungszeichenfolge hinzufügen, nicht ändern eine vorhandene – Thomas

9

Musste genau dieses Ding 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"); 
Verwandte Themen