Question : XML update / app.config update

my application is using an XML file to store it configuration information and I am storing the location of that XML within the app.config file via this code:


 
   
 



I was also informed that I could edit this value location with this set of code:


            System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection appSettings = cfg.AppSettings;
            appSettings.Settings["ConfigFileName"].Value = ConfigPathBox.Text;

            cfg.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection("appSettings");

However so far it isn't working. Any help would be great. This is realy important to my application working correctly.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
namespace AV4._1_ClientTool.Dialogs1.Configurations
{
    /*
     * The IP Address and Port # are needed when creating an AlphaNetClient object. This AlphaNetClient 
     * construct takes the IP Address and Port# and after assigning them to global variables, those 
     * variables are used when performing a TCP Client Connect() call. It is at this point the connection 
     * is made between the API and the exchange.
     */
    
    public partial class ServerConfigurations : Form
    {
        public ServerConfigurations()
        {
            InitializeComponent();
        }

        //read the XML file 
        private static string ConfigFileName = ConfigurationManager.AppSettings["ConfigFileName"];

        #region Text Field Display

        public void PopulateServerForm(object sender, EventArgs e)
        {
            // XElement.Load("File name with path") loads the XML file into myDoc 
            // File name without path, file gets place where the exe file is 
            // located, should be bin/debug in the project folder 
            XElement myDoc = XElement.Load(ConfigFileName);

            // Fill the text boxes with the values from the XML file 
            IPaddressBox.Text = myDoc.Descendants("IPAddress").FirstOrDefault().Value;
            IPportBox.Text = myDoc.Descendants("IPPort").FirstOrDefault().Value;
            ConfigPathBox.Text = myDoc.Descendants("ConfigurationPath").FirstOrDefault().Value;
        } 


       #endregion Text Field Display

        #region Buttons

        private void evOKPS1_Click(object sender, EventArgs e)
        {//upon Ok button pressed stores IP Address and IP Port then closes window

            string XmlFile = ConfigFileName;
            XElement myDoc = XElement.Load(XmlFile);

            // Save the values to the XML file from the text boxes 
            myDoc.Descendants("IPAddress").FirstOrDefault().Value = IPaddressBox.Text;
            myDoc.Descendants("IPPort").FirstOrDefault().Value = IPportBox.Text;
            myDoc.Descendants("ConfigurationPath").FirstOrDefault().Value = ConfigPathBox.Text;

            System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection appSettings = cfg.AppSettings;
            appSettings.Settings["ConfigFileName"].Value = ConfigPathBox.Text;

            cfg.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection("appSettings");


            myDoc.Save(XmlFile);

            this.Hide();
        }
        private void evApplyPS1_Click(object sender, EventArgs e)
        {//instantly stores IP Address and IP Port but does not close window
            //Store & Apply IPaddressBox, IPportBox, ConfigPathBox

            string XmlFile = ConfigFileName;
            XElement myDoc = XElement.Load(XmlFile);

            // Save the values to the XML file from the text boxes 
            myDoc.Descendants("IPAddress").FirstOrDefault().Value = IPaddressBox.Text;
            myDoc.Descendants("IPPort").FirstOrDefault().Value = IPportBox.Text;
            myDoc.Descendants("ConfigurationPath").FirstOrDefault().Value = ConfigPathBox.Text;
            ConfigurationManager.AppSettings["ConfigFileName"] = ConfigPathBox.Text;

            myDoc.Save(XmlFile);

        }

        private void DirButton1_Click(object sender, EventArgs e)
        {
            string Chosen_File = "";

            openFileDialog1.Title = "Configuration file locate";
            openFileDialog1.InitialDirectory = "C:";
            openFileDialog1.Filter = "XML Document|*.xml";
            DialogResult res = openFileDialog1.ShowDialog();

            if (res == DialogResult.OK) //OK clicked 
            {
                Chosen_File = openFileDialog1.FileName;
                ConfigPathBox.Text = Chosen_File;
            }
        }

        private void evCancelPS1_Click(object sender, EventArgs e)
        {//Closes the window without saving or editing information
            this.Close();
        }

        #endregion Buttons
    }
}

Answer : XML update / app.config update

OK... I'm using the newer Properties.Settings.Default classes rather than the older System.Configuration.ConfigurationManager.AppSettings technique.   This will require you to change your application.  Take a look at the documentation at:   http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx

Attached is a C# example of my original ConfigXML class.   You'd use it like this:


           // create an instance of the class
           ConfigXML c = new ConfigXML();
            // set the configuration settings to the new values
           c.SetValue(ConfigXML.Section.User, "SomeUserString","SomeNewValue");
           c.SetValue(ConfigXML.Section.Application, "SomeAppString", "SomeNewValue);
            // save the settings
           c.SaveSettings();

 

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
// Add a Reference to System.Configuration
using System;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Text;

namespace EE_ConfigXML
{

    //
    // Allows for the editing of key/value pairs in the config file. This required
    // because the My.Settings values for the Application scope are read only, and 
    // the values for User scope are recorded elsewhere.
    // Note: You can only change a value, you can not add or delete a key
    //
    public class ConfigXML
    {

        private Configuration cfg;
        private XmlDocument xd_app;
        private XmlDocument xd_user;
        private string AssemblyName;

        public enum Section : int
        {
            Application = 0,
            User
        }

        //
        // The default constructor loads the configuration file from the
        // currently running application
        //
        public ConfigXML()
        {
            cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AssemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

            LoadSections();
        }

        //
        // Load the configuration file for some other application
        //
        public ConfigXML(string ConfigPath, string ExpectedAssemblyName)
        {
            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            ConfigurationSectionGroup s = default(ConfigurationSectionGroup);

            if (File.Exists(ConfigPath))
            {
                map.ExeConfigFilename = ConfigPath;
                cfg = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

                // Get the Assembly name from the config file
                s = cfg.SectionGroups["applicationSettings"];
                if ((s == null))
                {
                    throw new ApplicationException("Configuration file missing, corrupt, or not the correct version");
                }
                AssemblyName = s.Sections[0].SectionInformation.Name.Split('.')[0];
                if (AssemblyName != ExpectedAssemblyName)
                {
                    throw new ApplicationException("Incorrect Configuration file\rExpecting configuration for " + ExpectedAssemblyName + ", however the configuration file is for " + AssemblyName);
                }
            }
            else
            {
                throw new System.IO.FileNotFoundException();
            }

            LoadSections();
        }

        //
        // Save the changes back to the config file
        //
        public void SaveSettings()
        {
            ConfigurationSection sec_app = default(ConfigurationSection);
            ConfigurationSection sec_user = default(ConfigurationSection);
            StringBuilder sb = default(StringBuilder);
            XmlWriterSettings xws = default(XmlWriterSettings);
            XmlWriter xw = default(XmlWriter);

            // Create settings for the XmlWriter to match the formatting of
            // the *.config file
            xws = new XmlWriterSettings();
            xws.Indent = true;
            xws.IndentChars = " ";
            xws.OmitXmlDeclaration = true;

            // prep the XmlWriter
            sb = new StringBuilder();
            xw = XmlWriter.Create(sb, xws);
            if ((xd_app != null))
            {
                xd_app.Save(xw);

                // replace the entire applicationSettings section
                sec_app = (ConfigurationSection)cfg.GetSection("applicationSettings/" + AssemblyName + ".Properties.Settings");
                sec_app.SectionInformation.SetRawXml(sb.ToString());
            }

            // do it again for the userSettings section
            sb = new StringBuilder();
            xw = XmlWriter.Create(sb, xws);
            if ((xd_user != null))
            {

                xd_user.Save(xw);
                sec_user = (ConfigurationSection)cfg.GetSection("userSettings/" + AssemblyName + ".Properties.Settings");
                sec_user.SectionInformation.SetRawXml(sb.ToString());
            }

            // save the changes to the config file
            cfg.Save();
        }

        //
        // Get a value from a key/value pair from the configuration file
        //
        public string GetValue(Section Sec, string Key)
        {
            XmlNode xn = default(XmlNode);

            xn = null;

            // Use XPath navigation to find the proper node
            switch (Sec)
            {
                case Section.Application:
                    if ((xd_app == null))
                    {
                        return null;
                    }

                    xn = xd_app.SelectSingleNode("//setting[@name=\"" + Key + "\"]");
                    break;
                case Section.User:
                    if ((xd_user == null))
                    {
                        return null;
                    }

                    xn = xd_user.SelectSingleNode("//setting[@name=\"" + Key + "\"]");
                    break;
            }

            if ((xn != null))
            {
                // is this a serialized string array?
                if (xn.InnerXml.StartsWith("";
                }
                else
                {
                    xn.InnerXml = "" + value + "";
                }
            }
        }

        //
        // Load the two XML documents with the appropriate section
        //
        private void LoadSections()
        {
            ConfigurationSection sec_app = default(ConfigurationSection);
            ConfigurationSection sec_user = default(ConfigurationSection);

            // get the applicationSettings section
            sec_app = (ConfigurationSection)cfg.GetSection("applicationSettings/" + AssemblyName + ".Properties.Settings");
            if ((sec_app != null))
            {
                // make an XmlDocument out of that section
                xd_app = new XmlDocument();
                xd_app.LoadXml(sec_app.SectionInformation.GetRawXml());
            }

            // do it again for the userSettings section
            sec_user = (ConfigurationSection)cfg.GetSection("userSettings/" + AssemblyName + ".Properties.Settings");
            if ((sec_user != null))
            {
                // make an XmlDocument out of that section
                xd_user = new XmlDocument();
                xd_user.LoadXml(sec_user.SectionInformation.GetRawXml());
            }
        }

        //
        // Convert an XML serialized string array into a string
        //
        private static string XMLStringArraytoString(string buf)
        {
            System.Xml.Serialization.XmlSerializer xmls = default(System.Xml.Serialization.XmlSerializer);
            StringReader sr = default(StringReader);
            string[] temp = null;

            // build a serializer that handles string arrays
            xmls = new System.Xml.Serialization.XmlSerializer(typeof(string[]));

            // do the deed
            sr = new StringReader(buf);
            temp = (string[])xmls.Deserialize(sr);
            if (temp.Length == 0)
            {
                return "";
            }

            return String.Join("\r\n", temp);
        }

        //
        // Convert a string array into an XML serialized string
        //
        private static string String2XMLStringArray(string buf)
        {
            System.Xml.Serialization.XmlSerializer xmls = default(System.Xml.Serialization.XmlSerializer);
            StringBuilder sb = default(StringBuilder);
            XmlWriter xw = default(XmlWriter);
            XmlWriterSettings xws = default(XmlWriterSettings);
            string[] temp = null;

            // trim any extra blank lines at the end
            buf = buf.TrimEnd("\r\n".ToCharArray());

            // build a string array
            temp = buf.Split("\r\n".ToCharArray());
            for (int i = 0; i <= temp.Length; i++)
            {
                temp[i] = temp[i].Trim('\n');
            }

            // setup the formatting options
            xws = new XmlWriterSettings();
            xws.Indent = true;
            xws.IndentChars = " ";
            xws.OmitXmlDeclaration = true;

            // prep the XmlWriter
            sb = new System.Text.StringBuilder();
            xw = System.Xml.XmlWriter.Create(sb, xws);

            // build a serializer that handles string arrays
            xmls = new System.Xml.Serialization.XmlSerializer(typeof(string[]));

            // do the deed
            xmls.Serialize(xw, temp);

            // add a bit of padding to each line
            temp = sb.ToString().Split("\r\n".ToCharArray());
            for (int i = 0; i <= temp.Length; i++)
            {
                temp[i] = " " + temp[i].Trim('\n');
            }

            return String.Join("\r", temp);
        }
    }
}
Random Solutions  
 
programming4us programming4us