E.S E.S - 2 months ago 8
C# Question

How to prevent reading app.config?

Sorry if this looks like a stupid question.

My application uses a connection string to connect to a SQL Server 2008 database and uses Crystal Report, my server use mix authentication mode.

The problem is:

app.config
file shows connection string (user name & password) which I don't want anyone to see!

Data Source=.\SQLEXPRESS;Initial Catalog=ComplainsDb;Persist Security Info=false; User ID=abcde ;Password=MyPassword


Thanks for any help.

Answer

You need to call something like this when your program starts:

    void EncryptConnectionStringsIfNecessary()
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ConnectionStringsSection section = configFile.ConnectionStrings;
        if (section != null)
        {
            if (!section.IsReadOnly())
            {
                if (!section.SectionInformation.IsProtected)
                {
                    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                    section.SectionInformation.ForceSave = true;
                    configFile.Save(ConfigurationSaveMode.Full);
                }
            }
        }
    }
Comments