1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
E.S
  • 536
  • 1
  • 9
  • 20

1 Answers1

3

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);
                }
            }
        }
    }
shamp00
  • 11,106
  • 4
  • 38
  • 81
  • That is work for me so far.. but how can i decrypt this file?? – E.S Sep 24 '13 at 06:42
  • 1
    You don't usually need to do anything. As explained in [the MSDN documentation](http://msdn.microsoft.com/en-us/library/hh8x3tas.aspx), the .NET framework will decrypt the settings automatically when you access `ConfigurationManager.ConnectionStrings[connectionStringName]`. – shamp00 Sep 24 '13 at 07:51
  • FYI: `ConfigFile` should be `configFile`. ;) – James Wilkins Sep 20 '16 at 23:46
  • Thanks @JamesWilkins. Updated. – shamp00 Sep 22 '16 at 20:20