C#

직렬화,역직렬화

J개발자 2020. 12. 5. 01:43

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Forms;

namespace 기말고사_공부하기
{
    public partial class Form1 : Form
    {
        ArrayList al;
        Card card;
        public Form1()
        {
            InitializeComponent();
            al = new ArrayList();
        }


        [Serializable]
        public class Card
        {
            public string name; public string phone; public string address;
        }


        private void button1_Click(object sender, EventArgs e)//입력 (Card라는 객체에 입력 정보를 저장)
        {
            MessageBox.Show("내용이 올바르게 입력 되었습니까?", "텍스트 박스");
            card = new Card();
            card.name = textBox1.Text;
            card.phone = textBox2.Text;
            card.address = textBox3.Text;
            al.Add(card);

            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
        }

        private void button2_Click(object sender, EventArgs e)//검색(이름을 갖는 요소의 인텍스를 구해 정보 출력)
        {
            bool ft = true;
            foreach(Card c in al)
            {
                if(c.name == textBox1.Text)
                {
                    textBox2.Text = c.phone;
                    textBox3.Text = c.address;
                    ft = false;
                    break;
                }
            }
            if (ft) MessageBox.Show("존재하지 않음");
        }

        private void button3_Click(object sender, EventArgs e)//다음(Arraylist 다음 항목을 출력하고 현 항목이 마지막일시 맨앞)
        {
            int j;
            foreach(Card c in al)
            {
                if(c.name == textBox1.Text)
                {
                    j = al.IndexOf((object)c);   //해당 이름이 저장된 ArrayList의 인덱스값을 j에 저장

                    if (al.Count == j + 1) j = -1;  //마지막일 경우 맨 앞으로 이동

                    Card c2 = (Card)al[j + 1];
                    textBox1.Text = c2.name;
                    textBox2.Text = c2.phone;
                    textBox3.Text = c2.address;
                    break;
                }
            }

        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)//읽기(ArrayList객체로 역직렬화시키고 Card객체를 출력)
        {
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open); //객체를 저장하는 파일 생성,스트림 객체 얻음.
                al.Clear();

                BinaryFormatter bf1 = new BinaryFormatter(); //객체로 역질려화 하기 위해서 
                al = (ArrayList)bf1.Deserialize(fs); //파일로부터 읽은 객체를 리스트 객체로 역직렬화
                Card cc = (Card)al[0];
                textBox1.Text = cc.name;  //textBox1.Text = ((Card)al[0]).name;
                textBox2.Text = cc.phone;
                textBox3.Text = cc.address;
                fs.Close();


            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)//저장(저장대화상자 수행후 입력 파일로 ArrayList객체 직렬화)
        {
            if(saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create); //객체 저장하는 파일생성,스트림 객체 얻음,
                BinaryFormatter bf = new BinaryFormatter(); //바이너리 형식으로 직렬화하기 위해
                bf.Serialize(fs, al);//어레이리스트 객체를 바이너리 형식으로 직렬화
                fs.Close();
            }
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
    }
}

Card 클래스를 분리하여 다른 cs파일로 작성해도 됨. //?????

 

 

 

 

 

 

 

 

 

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Forms;

namespace 기말고사_공부하기
{
    public partial class Form1 : Form
    {
        ArrayList al;
        public Form1()
        {
            InitializeComponent();
            al = new ArrayList();
        }

        private void button1_Click(object sender, EventArgs e)//추가버튼
        {
            ListViewItem i = new ListViewItem(textBox1.Text, comboBox1.SelectedIndex);
            i.SubItems.Add(textBox2.Text);
            i.SubItems.Add(textBox3.Text);
            i.SubItems.Add(comboBox1.SelectedItem.ToString());
            listView1.Items.Add(i);

            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";


        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)//저장(직렬화)
        {
            saveFileDialog1.ShowDialog();
            al.Clear();
            foreach(ListViewItem a in listView1.Items)
            {
                al.Add(a);
            }
            FileStream f = new FileStream(saveFileDialog1.FileName, FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(f, al);
            f.Close();

        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)//열기(읽기)(역직렬화)
        {
            openFileDialog1.ShowDialog();
            FileStream f = new FileStream(openFileDialog1.FileName, FileMode.Open);
            BinaryFormatter bf = new BinaryFormatter();
            al = (ArrayList)bf.Deserialize(f);
            listView1.Items.Clear();
            foreach (ListViewItem i in al)
                listView1.Items.Add(i);
            f.Close();

        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            listView1.View = View.LargeIcon;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            listView1.View = View.SmallIcon;
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            listView1.View = View.List; //간단히
        }

        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            listView1.View = View.Details;
        }
    }
}