简体   繁体   中英

ConfigurationManager.ConnectionString reads app.config from different location

The app.config of my C# windows application has the following ConnectionString

<connectionStrings>
    <add name="DS1" connectionString="Data Source=DataSource1;" providerName="" />
    <add name="DS2" connectionString="Data Source=DataSource2;" providerName="" />
    <add name="DS3" connectionString="Data Source=DataSource3;" providerName="" />
    <add name="DS4" connectionString="Data Source=DataSource4;" providerName="" />
</connectionStrings>

After installing the setup, the same connection strings exist in the projectname.config of installation directory C:\\ProgramFiles\\ProjectName\\ProjectName.config.

When i run the application, i have the following code to access the connection string

foreach (ConnectionStringSettings key in ConfigurationManager.ConnectionStrings)
        {
            Display ConfigurationManager.ConnectionStrings[key.Name].Name,

        }

The Key names are not displaying as DS1, DS2, DS3 and DS4 .

Instead it is reading the ProjectName.config file present in

C:\Users\UserName\AppData\Local\VirtualStore\Program Files\ProjectName\ProjectName.exe.config

This was saved long back when project was installed but when uninstalled it doesn't get removed.

How can i make changes in C# to read the proper ProjectName.config file from installation dircectory and not from AppData folders.

Try this

 string theConfigFileName ="FilePath";
 ExeConfigurationFileMap userConfigFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = theConfigFileName };
 Configuration userConfig = ConfigurationManager.OpenMappedExeConfiguration(userConfigFileMap, ConfigurationUserLevel.None);

foreach (var item in userConfig.ConnectionStrings.ConnectionStrings)
{

} 

On app startup you could check for the existence of the original config and delete it.

string originalConfig = string.Format("C:\Users\{0}\AppData\Local\VirtualStore\Program Files\ProjectName\ProjectName.exe.config", Environment.UserName);

if (System.IO.File.Exists(originalConfig))
{
    System.IO.File.Delete(originalConfig);
}

If you wanted to do it during the uninstall, you could execute this code in a custom action:

System.IO.Directory.Delete("%APPDATA%\ProjectName");

See msdn for creating a custom action

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