Shai
Shai

Reputation: 569

Dynamically creating App.config with connection string if App.config does not exists in Application-Data folder

I need to do my code the following task. I wrote some code as below, but I am getting error while setting connection string. Looks like it does not have set property.

  1. Check if App.config is exists in user’s “Application Data” folder.

  2. If does NOT exists then create App.config with ConnectionString

  3. If does exists then check if it was connection string or not, and if missing then add connection string.

    string SomeConnectionString ="My Connection String goes here"
    
    //Checking whether App.config file exits in "Application Data" folder or not
      String appDataPath = Environment.GetFolderPath
                       (Environment.SpecialFolder.LocalApplicationData);
    
      if (!File.Exists(appDataPath + "App.config"))
        {
           appDataPath = Path.Combine(appDataPath , "App.config");
           Configuration config = ConfigurationManager.OpenExeConfiguration
                                  (appDataPath );
           var setting = config.ConnectionStrings.ConnectionStrings
                         ["MyConnectionString"]; 
    
           if (setting == null) 
           { 
               Configuration Config = ConfigurationManager.OpenExeConfiguration
                                      (ConfigurationUserLevel.None);
               config.ConnectionStrings.ConnectionStrings
                ["MyConnectionString"].ConnectionString = SomeConnectionString; 
                 //I am getting error on line above. Looks like there is not set 
                 //property on it
    
            Config.Save(ConfigurationSaveMode.Modified,true);
            ConfigurationManager.RefreshSection("connectionStrings");
          }
    
        }
        else
        {
            //check whether it has Connection string or not
            //if not then add connection string 
        }
    

Upvotes: 0

Views: 3234

Answers (2)

Brian Lyttle
Brian Lyttle

Reputation: 14579

Have you looked at the Settings API? This might be more appropriate for what you are doing.

Upvotes: 1

Fischermaen
Fischermaen

Reputation: 12458

The app.config is only that named in your program. During build process the file is renamed to [ApplicationName].exe.config. So name the file like this. But beware! Normally the program directory is not allowed for write access (only to administrators). Settings-API is the better way!!!!

Upvotes: 2

Related Questions