I have a program that allows the user to open xml files and edit them, then save them. The thing is, when I open a config file, (.exe.config), it saves and overwrites properly but the whole file loses its formatting and becomes one huge, long, single line. Of course with my program the user will never see that it is one line, so it is not a major problem with the functionality of my program, but does anyone know how to keep the format of the configuration xml file as it was? When I open it I'm simply changing the setting values, nothing more. I did not do anything to the format/indentation to my knowledge. Or perhaps have some insight as to why it is doing this?
Many thanks!
Tf.rz
EDIT: Here is the code:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;
namespace WindowsFormsApplication4
{
public partial class ProgramConfig : Form
{
public ProgramConfig()
{
InitializeComponent();
}
private XmlDocument m_XmlDoc;
private FileStream fIn;
private StreamReader sr;
private StreamWriter sw;
private OrderedDictionary m_Settings;
private int m_savecounter = 0;
private void ProgramConfig_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = "File open: " + GatewayConfiguration.Properties.Settings.Default.Config;
int index = 0;
loadconfigfile(GatewayConfiguration.Properties.Settings.Default.Config);
string[] keys = new string[m_Settings.Keys.Count];
m_Settings.Keys.CopyTo(keys, 0);
string[] values = new string[m_Settings.Values.Count];
m_Settings.Values.CopyTo(values, 0);
BindingList<KeyValueType> list = new BindingList<KeyValueType>();
for (index = 0; index < m_Settings.Count; index++)
{
list.Add(new KeyValueType(keys[index], values[index].ToString()));
}
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
dataGridView1.Columns[0].Name = "Key";
dataGridView1.Columns[0].DataPropertyName = "key";
dataGridView1.Columns[1].Name = "Value";
dataGridView1.Columns[1].DataPropertyName = "value";
var source = new BindingSource();
source.DataSource = list;
dataGridView1.DataSource = source;
for (index = 0; index < dataGridView1.Columns.Count; index++)
{
// Auto resize while keeping user resize true.
dataGridView1.Columns[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
int initialAutoSizeWidth = dataGridView1.Columns[index].Width;
dataGridView1.Columns[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
dataGridView1.Columns[index].Width = initialAutoSizeWidth;
}
dataGridView1.ReadOnly = false;
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
dataGridView1.Columns[2].Name = "New Value";
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
}
private void loadAppSettings()
{
m_Settings = new OrderedDictionary();
XmlNodeList nl = m_XmlDoc.GetElementsByTagName("setting");
foreach (XmlNode node in nl)
{
try
{
m_Settings.Add(node.Attributes["name"].Value, node.ChildNodes[0].InnerText);
}
catch (Exception)
{
}
}
}
public void loadconfigfile(string configfile)
{
if (File.Exists(configfile))
{
m_XmlDoc = new XmlDocument();
GatewayConfiguration.Properties.Settings.Default.Config = configfile;
GatewayConfiguration.Properties.Settings.Default.Save();
fIn = new FileStream(configfile, FileMode.Open, FileAccess.ReadWrite);
sr = new StreamReader(fIn);
sw = new StreamWriter(fIn);
try
{
m_XmlDoc.LoadXml(sr.ReadToEnd());
m_XmlDoc.PreserveWhitespace = true;
loadAppSettings();
}
catch (Exception ex)
{
throw ex;
}
}
else
{
throw new FileNotFoundException(configfile + " does not exist.");
}
}
private void SaveAppSettings_Click(object sender, EventArgs e)
{
MessageBoxButtons 开发者_高级运维buttons = MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show("Overwrite the old values with the new values?", "Save Settings?", buttons);
if (result == DialogResult.No)
{
return;
}
int index = 0;
string[] keys = new string[m_Settings.Keys.Count];
m_Settings.Keys.CopyTo(keys, 0);
for (index = 0; index < dataGridView1.Rows.Count; index++)
{
if ((string)dataGridView1[2, index].Value != string.Empty)
{
setAppSetting(keys[index], (string)dataGridView1[2, index].Value);
}
}
textBox1.Text = "Settings Saved. You may now exit.";
m_savecounter++;
dataGridView1.Update();
dataGridView1.Refresh();
}
public void setAppSetting(string name, string newValue)
{
if (!m_Settings.Contains(name))
{
throw new Exception(String.Format("Setting {0} does not exists in {1}", name, GatewayConfiguration.Properties.Settings.Default.Config));
}
else
{
if (newValue == null || m_Settings[name].ToString() == newValue)
{
return;
}
m_Settings[name] = newValue;
m_XmlDoc.SelectSingleNode("//setting[@name='" + name + "']").ChildNodes[0].InnerXml = newValue;
fIn.SetLength(0);
sw.Write(m_XmlDoc.InnerXml);
sw.Flush();
}
}
public class KeyValueType
{
private string _key;
public string Key
{
get
{
return _key;
}
}
private string _value;
public string Value
{
get
{
return _value;
}
}
public KeyValueType(string key, string value)
{
_key = key;
_value = value;
}
}
private void ProgramConfig_FormClosing(object sender, FormClosingEventArgs e)
{
if (m_savecounter == 0)
{
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show("You have not saved, still want to exit?", "Exit?", buttons);
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
sw.Close();
sr.Close();
fIn.Close();
}
}
}
If you are using XmlDocument
you can set the PreserveWhitespace
property to true - it defaults to false if not set.
The equivalent for XDocument
is the Load()
overload with LoadOptions.PreserveWhitespace
.
精彩评论