How to add connectionstring and appsettings to a web.config uisng Web Setup.

Hi All,

I am building the web setup fo my site for production. Now my requirement is to add a connection string and couple of appsettings to the web config during the setup of the web app. The set up should give me an option of setting the connection string and appsettings.

I am trying the following code, found at some post but without any success.

where targetVDir, targetSite  are coming from the custom action in the setup which has the following setup. connection string is coming from the textbox whihc is custom dialog box actin in the setup.

/connectionstring="[EDITA1]" /targetvdir="[TARGETVDIR]" /targetsite="[TARGETSITE]"

Please advice ASAP.


namespace CustomWebConfigInstaller
    public class CustomWebConfig:Installer
        const string DATABASE_CONNECTION_KEY = "eAdjudication";
        public override void Install(System.Collections.IDictionary stateSaver)
            string targetSite = "W3SVC";//Context.Parameters["targetsite"]; //
            if (targetSite == null)
                throw new Exception("Site name is null");
            string targetVDir = Context.Parameters["targetvdir"]; //"MyApp";//
            if (targetVDir == null)
                throw new Exception("Virtual Dir is null");
            string connectionString = Context.Parameters["connectionstring"];//"Data Source=localhost;Initial Catalog=eAdjudication_Cap;Persist Security Info=True;User ID=devsa;Password=welcome2adc!";
            if (connectionString == null)
                throw new Exception("Conection String is null");
            this.ConfigureDatabase(targetSite, targetVDir, connectionString);
        void ConfigureDatabase(string targetSite, string targetVDir, string connectionString)
            // Retrieve "Friendly Site Name" from IIS for TargetSite
            DirectoryEntry entry = new DirectoryEntry("IIS://LocalHost/" + targetSite);
            string friendlySiteName = entry.Properties["ServerComment"].Value.ToString();
            // Open Application's Web.Config
            Configuration config = WebConfigurationManager.OpenWebConfiguration("/" + targetVDir, friendlySiteName);
            // Add new connection string setting for web.config
            ConnectionStringSettings appDatabase = new ConnectionStringSettings();
            appDatabase.Name = DATABASE_CONNECTION_KEY;
            appDatabase.ConnectionString = connectionString;
            // Persist web.config settings

Open in new window

Who is Participating?
rajan_thakur78Connect With a Mentor Author Commented:

The above code which i posted worked for me.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.