C# winform 怎么保存一个对象到文本文件中 (和读取)

解决方案 »

  1.   

    System.IO.StreamWriter
    System.IO.StreamReader
      

  2.   

    对象必须是 [Serializable()]  [Serializable()] 
        class EntryClass
        {
            private string name;
            public  EntryClass()
            {
                name = "";        }
            public  EntryClass(string dd)
            {
                name = dd;        }
            public string GetName()
            {
                return name;
            }    }using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime;
    using System.IO;namespace EntryClassSerialize
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private void Read_Click(object sender, EventArgs e)
            {
                System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                Stream stream = new FileStream("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
                EntryClass myBlock = (EntryClass)formatter.Deserialize(stream);
                stream.Close();
                this.textBox1.Text = myBlock.GetName();
            }        private void Save_Click(object sender, EventArgs e)
            {
                EntryClass myBlock = new EntryClass(textBox2.Text);
               System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                Stream stream = new FileStream("MyFile.txt", FileMode.Create, FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, myBlock);
                stream.Close();         }
        }
    }