简体   繁体   中英

How to move connectionString from App.config to code in C#?

I want to remove connectionString from App.config and add it to code. I'm using WinForms(C#) and.Net Framework 4.8. I have textBoxes and a datagridview on my form. I'm using Microsoft Access Database (.mdb). I want to do this because database's password is visible in App.config. Is there any way to do that

Here is my app.config XML code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Locker.Properties.Settings.pw_dbConnectionString"
            connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\files\pw_db.mdb;Persist Security Info=True;Jet OLEDB:Database Password=XYZ"
            providerName="System.Data.OleDb" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
</configuration>

I would suggest you not to define the connection string in code, better you can encrypt it in the app.config file.

Please follow the following steps:

  • Rename app.config to web.config
  • Open command prompt and type: %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" path of the web.config>
  • Rename web.config back to app.config

If you open the file in notepad, you will see the encrypted value and you can continue using it as you were using before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM