@manhng

Welcome to my blog!

Update Config File

June 11, 2020 11:18

Update Config File (edit)

private void UpdateConfigFile(string appConfigPath, string key, string value)

https://stackoverflow.com/questions/5274829/configurationmanager-appsettings-how-to-modify-and-save

Change .config File at Runtime C# Code

https://yizeng.me/2013/08/31/update-appsettings-and-custom-configuration-sections-in-appconfig-at-runtime/

Building a better .NET Application Configuration Class - revisited

https://weblog.west-wind.com/posts/2012/dec/28/building-a-better-net-application-configuration-class-revisited

Show me the code


// ---------- Validation ----------
var isSQLCommandTimeoutWrong = int.TryParse(txtSQLCommandTimeout.Text.Trim(), out int intSQLCommandTimeout);
if (!isSQLCommandTimeoutWrong)
{
MessageBox.Show("SQL Command Timeout is not correct");
txtSQLCommandTimeout.Focus();
return false;
}

// ---------- Load ----------
try
{
var appConfigContent = File.ReadAllText(webConfigFileName);
var searchedString = $"<add key=\"SQLCommandTimeout\" value=\"";
var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
var strSQLCommandTimeout = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
txtSQLCommandTimeout.Text = strSQLCommandTimeout;
}
catch
{
}

// ---------- SQL Command Timeout ----------
private void UpdateConfigFile(string appConfigPath, string key, string value)
{
var appConfigContent = File.ReadAllText(appConfigPath);
var searchedString = $"<add key=\"{key}\" value=\"";
var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
var newValue = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{value}\"");
File.WriteAllText(appConfigPath, newValue);
}

Categories

Recent posts