Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 修改xml配置文件会产生一行文件_C#_Xml - Fatal编程技术网

C# 修改xml配置文件会产生一行文件

C# 修改xml配置文件会产生一行文件,c#,xml,C#,Xml,我有一个程序,允许用户打开xml文件并编辑它们,然后保存它们。问题是,当我打开一个配置文件(.exe.config)时,它会正确地保存和覆盖,但整个文件会丢失格式,变成一个巨大的、很长的单行。当然,对于我的程序,用户永远不会看到它是一行,因此这不是我程序功能的主要问题,但是有人知道如何保持配置xml文件的格式不变吗?当我打开它时,我只是简单地更改设置值,仅此而已。据我所知,我没有对格式/缩进做任何修改。或者也许对它为什么这样做有一些见解 非常感谢 Tf.rz 编辑: 代码如下: using Sy

我有一个程序,允许用户打开xml文件并编辑它们,然后保存它们。问题是,当我打开一个配置文件(.exe.config)时,它会正确地保存和覆盖,但整个文件会丢失格式,变成一个巨大的、很长的单行。当然,对于我的程序,用户永远不会看到它是一行,因此这不是我程序功能的主要问题,但是有人知道如何保持配置xml文件的格式不变吗?当我打开它时,我只是简单地更改设置值,仅此而已。据我所知,我没有对格式/缩进做任何修改。或者也许对它为什么这样做有一些见解

非常感谢

Tf.rz

编辑: 代码如下:

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();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Collections.Specialized;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.IO;
使用System.Windows.Forms;
使用系统配置;
使用System.Xml;
命名空间Windows窗体应用程序4
{
公共部分类ProgramConfig:Form
{
公共程序配置()
{
初始化组件();
}
私有XmlDocument m_XmlDoc;
私人文件流fIn;
私人流动阅读器sr;
私人StreamWriter sw;
私人订购的字典m_设置;
私有整数m_savecounter=0;
私有void ProgramConfig_加载(对象发送方,事件参数e)
{
尝试
{
textBox1.Text=“文件打开:”+GatewayConfiguration.Properties.Settings.Default.Config;
int指数=0;
loadconfigfile(GatewayConfiguration.Properties.Settings.Default.Config);
string[]keys=新字符串[m_Settings.keys.Count];
m_设置.key.CopyTo(key,0);
字符串[]值=新字符串[m_Settings.values.Count];
m_Settings.Values.CopyTo(值为0);
BindingList=新建BindingList();
对于(索引=0;索引