I need to pragmatically update an auto generated app.config file of a Windows Form.
Specifically an ArrayOfStrings.
Desired out put:
<setting name="Test" serializeAs="Xml">
<value>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Test 1</string>
<string>Test 2</string>
<string>Test 3</string>
</ArrayOfString>
</value>
</setting>
What my code generates:
<setting name="Test" serializeAs="Xml">
<value>New Data 3</value>
</setting>
I have researched Xml serialization, but it is completely new to me and I am struggling to figure it out.
public void saveCardDataToSettings() {
List<String> DetectorCardTypeData = new List<string>();
foreach (DataGridViewRow row in dgvDetectorCardData.Rows)
{
string CurrentRowData = (row.Cells[0].Value + "," + row.Cells[2].Value + "," + row.Cells[4].Value);
DetectorCardTypeData.Add(CurrentRowData);
}
StringCollection TestData = new StringCollection();
foreach (string CardData in DetectorCardTypeData)
{
TestData.Add(CardData);
}
//Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup applicationSectionGroup = config.GetSectionGroup("applicationSettings");
ConfigurationSection applicationConfigSection = applicationSectionGroup.Sections["EXP_Battery_Calculator.Properties.Settings"];
ClientSettingsSection clientSection = (ClientSettingsSection)applicationConfigSection;
SettingElement appData = clientSection.Settings.Get("Test");
foreach (string WriteME in TestData)
{
appData.Value.ValueXml.InnerText = WriteME;
clientSection.Settings.Add(appData);
}
applicationConfigSection.SectionInformation.ForceSave = true;
config.Save();
listBox1.DataSource = TestData;
}
Still can't understand why need to store data in the application config, but anyway.
First of all, create a new parameter in your Settings file. Name it as you want ("StoredData" in example below), set type to
System.Collections.Specialized.StringCollections, set scope "Application" and add default value (i've added "Empty"). This should produce an XML string:and also will modify default config:
To edit
ArrayOfStringnode i've used this code:That example, after
config.Savecall immediately rewrites config and produces such look:BUT it doesn't updates
Property.Settings.Default.StoredDataproperty at runtime. Only after application restart it will load modified data from config. It also doesn't modifies "App.config" in your project folder. Only "YourAssemblyName.exe.config" near your output binary file.Not sure this way is appropriate or applicable. Still didn't understand why you decided to punish little config file in such way. You have user-scoped settings for that. Or just write own separate file such as "myStoredData.xml" in application directory.