-1

I am working on a web application which extracts data from databases. Databases are residing on server. I want the user to provide Server Name, username and password from the web application, which will help me to modify my connection string in web.config file from the code behind page. So, how can I update the config file from the code behind page in C#?

Guide me on what do I need to do here.

Rashmin Javiya
  • 5,173
  • 3
  • 27
  • 49
Perk
  • 31
  • 6
  • 1
    Why not build up a `IDbConnection` instead of edit the web.config? Editing the web.config will make the changes active for all current users. – Davin Tryon Jun 12 '14 at 11:09
  • Share the code you have done so far – Devesh Jun 12 '14 at 11:09
  • 1
    http://stackoverflow.com/questions/719928/how-do-you-modify-the-web-config-appsettings-at-runtime – Prabhakaran Parthipan Jun 12 '14 at 11:09
  • @Davin:IDbConnection?? – Perk Jun 12 '14 at 11:18
  • @Perk yes [IDbConnection](http://msdn.microsoft.com/en-us/library/system.data.idbconnection.aspx). Maybe [SqlConnectionStringBuilder](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx) will help as well. – Davin Tryon Jun 12 '14 at 11:32
  • If server, user name and password are user-specific settings, then they belong on the client side, not in your web application's config file (which is very likely located on the server side). – stakx - no longer contributing Jun 12 '14 at 11:49
  • @stakx because, my application will take connection string and other parameters from config file, i want to update the same as per user requirement – Perk Jun 12 '14 at 11:57

1 Answers1

0

Refer the code below:

// using System.Configuration;
// using System.IO;
var fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = File.Exists("XYZ.exe.config") ? "XYZ.exe.config" : "XYZ.config";
string path = Path.Combine(Application.StartupPath, key);
if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}
var config = System.Configuration.Configuration; 
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings.Item(key).Value = path;
config.Save(ConfigurationSaveMode.Modified);
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Ankit Goel
  • 353
  • 1
  • 4
  • 13
  • That answer would've been better if (1) you would only have posted the relevant bit of code, (2) explained it, and (3) posted C# code instead of VB.NET code (since the question is tagged C#) -- I've taken care the last issue. – stakx - no longer contributing Jun 14 '14 at 23:55