raven daniel

raven daniel

  • 1.3k
  • 123
  • 41.3k

C# winforms, How to persist Changes in my app.config?

Feb 27 2014 8:57 AM
Hi guys thanks for the time to help me out.
i got a Entity Framework datalayer, on a new project and im checking things out with it.
my starting form is a settings forms where you can type the server, datasource, Intergrated security (checkbox), username, password.
So the user may change this.
My issue was i couldn't make persisting changes to the connection string of my app.config, or more realistic not sure how.
I have only been successful in making changes to whats in memory as i debug my project.
my work around was to save values to text file in the project directory and just get those values and set them as my global verables so i can change the app.config in memory everytime i load the project.
///Declare my string builder
StringBuilder s = new StringBuilder();
 
///Make my Connection String from my global verables.
 s.Append("metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=\";"
+ "data source=" + Program.g_s_Server + ";"
+ "initial catalog=" + Program.g_s_Datasource + ";"
+ "integrated security=True;"
+ "User ID =" + Program.g_s_Uid + ";"
+ "Password=" + Program.g_s_Pwd + ";"
+ "App=EntityFramework\";");
 
///Change my app.config
 XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
   if (xElement.Name == "connectionStrings")
   {

      foreach (XmlNode xNode in xElement.ChildNodes)
      {
         if (xNode.Attributes[0].Value == "MyEntities")
         {
         xNode.Attributes[1].Value = s.ToString();
         }
      }
   }
}
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("connectionStrings");
 
 //This is just to see the change when i debug
var connection =
System.Configuration.ConfigurationManager.ConnectionStrings["MyEntities"];
 
 
 
 
So my Question is firstly most important now, how to persist the changes. Secondly should i use entity framework in my winform project as a datalayer or is there better?

Answers (1)