Search code examples
c#visual-studioconfigurationmanager

Updating my App.config Connection String from a text box


I want the user to be able to edit the connection string, I've set up a file browser dialogue where they can only select .accdb files, and I'm trying to have the save button overwrite the current connection string with the file path from the text box. I've had multiple errors at different times and I've ended up with a setup that seems tantalisingly close to working but I have a NullReferenceException error which says "Object reference is not set to an instance of an object". Hopefully this is a newbie mistake.

var configuration = ConfigurationManager.OpenExeConfiguration(@"\\Mac\Home\Documents\Visual Studio 2015\Projects\tiddlywinks\tiddlywinks\App.config");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["tiddlywinksDatabaseConnectionString1"].ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source ='" + filePathTextBox.Text + "'; Persist Security Info=False;";
configuration.Save();

This is the code that I have atm. Can anyone help?
Also, is there a way to achieve the same without having to tell the program where App.config is, surely Visual Studios knows where it's own config files are?


Solution

  • You can do that this way: You go to your solution properties

    Properties => Settings => Add new Settings

    (Make sure Scope is "user")

    and add a new sitting for your connection string, let's call it : ConnectionString

    like mentioned in this post: Applications sittings

    then all you have to do is

    Properties.Settings.Default.ConnectionString = TextBoxConnectionString.Text
    Properties.Settings.Default.Save();
    

    Give it a try, Hope it helps !