简体   繁体   中英

How to write / read multi-line text in an XML file?

I'm trying to save some application settings to an XML file. To do this, I use the following code in a single Props.cs file:

using System;
//надо добавить для работы класса
using System.Xml.Serialization;
using System.IO;


namespace SettingWinForm
{
    //Класс определяющий какие настройки есть в программе
    public class PropsFields
    {
        public String XMLFileName = Environment.CurrentDirectory + "\\settings.xml";
        //Чтобы добавить настройку в программу просто добавьте туда строку вида -
        //public ТИП ИМЯ_ПЕРЕМЕННОЙ = значение_переменной_по_умолчанию;
        public String TextValue = @"File Settings";
        public DateTime DateValue = new DateTime(2011, 1, 1);
        public Decimal DecimalValue = 555;
        public Boolean BoolValue = true;
    }
    //Класс работы с настройками
    public class Props
    {
        public PropsFields Fields;

        public Props()
        {
            Fields = new PropsFields();
        }
        //Запись настроек в файл
        public void WriteXml()
        {
            XmlSerializer ser = new XmlSerializer(typeof(PropsFields));

            TextWriter writer = new StreamWriter(Fields.XMLFileName);
            ser.Serialize(writer, Fields);
            writer.Close();
        }

        //Чтение настроек из файла
        public void ReadXml()
        {
            if (File.Exists(Fields.XMLFileName))
            {
                XmlSerializer ser = new XmlSerializer(typeof(PropsFields));
                TextReader reader = new StreamReader(Fields.XMLFileName);
                Fields = ser.Deserialize(reader) as PropsFields;

                reader.Close();
            }
            else
            {
                //можно написать вывод сообщения если файла не существует
            }
        }
    }
}

I also have a Form in a Form1.cs file that contains textBox1 , comboBox1 , checkBox1 , and two Button s.

using System;
using System.Windows.Forms;

namespace SettingWinForm
{
    public partial class Form1 : Form
    {
        #region Settings action
        Props props = new Props(); //экземпляр класса с настройками 
        //Запись настроек
        private void writeSetting()
        {
           props.Fields.TextValue = textBox1.Text;
           props.Fields.TextValue = comboBox1.Text;
           props.Fields.BoolValue = checkBox1.Checked;     
           props.WriteXml();
        }

        private void readSetting()
        {
            props.ReadXml();

            textBox1.Text = props.Fields.TextValue;
            comboBox1.Text = props.Fields.TextValue;
            checkBox1.Checked = props.Fields.BoolValue;
        }
        #endregion

        #region Form Action
        public Form1()
        {
            InitializeComponent();
        }           
        #endregion

        private void button1_Click_1(object sender, EventArgs e)
        {
            writeSetting(); 
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            readSetting();
        }

        // Очистить 
        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            comboBox1.Text = "";
            checkBox1.Checked = false;
        }
    }
}

在此处输入图片说明

How can I read and write multi-line text from textBox1 to an XML file?

What you have will work fine for saving and reading text from textBox1, whether single or multi-line. The problem in the code you've shown is you are saving both the textBox1 text AND then the comboBox1 text to the same field, TextValue . You are overwriting the first value with the second.

You need to create a new text field (ie TextValue2 ) for the comboBox text. Or maybe store the comboBox index value instead into DecimalValue if it is not editable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM