프로그램/C# - Study / / 2010. 10. 13. 15:13

C# - Ex23IO - 파일입출력( XmlSerializer, SoapFormatter, Serialization )

반응형

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

namespace Ex23IO
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Write Data Using Stream
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length == 0)
            {
                MessageBox.Show("출력할 내용이 없습니다.");
                return;

            }
            FileStream stream = new FileStream("test1.txt", FileMode.Create, FileAccess.Write, FileShare.None);

 

            // char[] => byte[]  변경 작업을 꼭 해줘야 한다!!!
            byte[] data = Encoding.Default.GetBytes(textBox1.Text);
            stream.Write(data, 0, data.Length);

            stream.Close();

            textBox1.Clear();
            MessageBox.Show("파일에 데이터를 썼습니다.");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!File.Exists("test1.txt")) // 파일 존재 여부 확인
            {
                MessageBox.Show("먼저 파일을 만들어야 합니다.");
                return;
            }
            textBox2.Clear();             //  @"d:\test1.txt" 이런식으로 하면 파일의 위치 지정불러옴
            FileStream stream = new FileStream("test1.txt", FileMode.Open,
                FileAccess.Read, FileShare.None);

            byte[] buffer = new byte[1024];
            while (true)
            {
                int count = stream.Read(buffer, 0, buffer.Length);
                if (count > 0)
                {
                             // byte[] -> char[]
                    string data = Encoding.Default.GetString(buffer, 0, count);
                    textBox2.AppendText(data);

                }
                else
                {
                    break;
                }
            }
            stream.Close();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            FileStream stream =
                new FileStream("test2.txt", FileMode.Create);

            StreamWriter writer = new StreamWriter(stream, Encoding.GetEncoding("euc-kr"));

            writer.WriteLine(textBox1.Text);

            writer.Close();
            stream.Close();
            MessageBox.Show("파일에 데이터를 썼습니다.");

        }

        private void button4_Click(object sender, EventArgs e)
        {
            StreamReader reader = new StreamReader("test2.txt", Encoding.GetEncoding("euc-jp"));
            while(true)
            {
                string data = reader.ReadLine();
                if(data != null)
                {
                    textBox2.AppendText(data + " \r\n");
                }
                else
                {
                    break;
                }               
            }
            reader.Close();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            FileStream stream = new FileStream("test3.dat", FileMode.Create);
            FileStream stream2 = new FileStream("test3.txt", FileMode.Create);

            BinaryWriter writer = new BinaryWriter(stream); //  성능
            StreamWriter writer2 = new StreamWriter(stream2); // 호환성

            for(int i = 0; i < 10000; i++)
            {
                writer.Write(int.MaxValue);
                writer2.Write(int.MaxValue);
            }
            writer.Close();
            writer2.Close();
            stream.Close();
            stream2.Close();

            MessageBox.Show("파일 작성 끝");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            FileStream stream = new FileStream("test3.dat", FileMode.Open);
            BinaryReader reader = new BinaryReader(stream);

            textBox2.AppendText(reader.ReadInt32() + "\r\n");
            textBox2.AppendText(reader.ReadInt32() + "\r\n");
            textBox2.AppendText(reader.ReadInt32() + "\r\n");
            textBox2.AppendText(reader.ReadInt32() + "\r\n");

            reader.Close();
            stream.Close();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Person person = new Person();
            person.Name = "장돈건";
            person.Email = "newtoynt@nate.com";

            FileStream stream = new FileStream("test4.dat", FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, person);
            stream.Close();


            //XmlSerializer   XML 형식으로 만들기
            FileStream stream2 =
                new FileStream("test4.xml", FileMode.Create);
            XmlSerializer s = new XmlSerializer(typeof(Person));
            s.Serialize(stream2, person);
            stream2.Close();

            //SoapFormatter  웹서비스 쪽에서 사용하는 특수한 xml
            FileStream stream3 =
                new FileStream("test4.soap", FileMode.Create);
            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(stream3, person);
            stream3.Close();

            MessageBox.Show("데이터 기록 끝");
        }

        private void button8_Click(object sender, EventArgs e)
        {
            FileStream stream =
                new FileStream("test4.dat", FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();
            Person person = (Person)formatter.Deserialize(stream);
            stream.Close();
            textBox2.AppendText("Name : " + person.Name +
                " / Email : " + person.Email);

        }
    }

    [Serializable] //Attribute : Serialization 가능한 객체 표시
    public class Person
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private string email;
        public string Email
        {
            get { return email; }
            set { email = value; }
        }
    }


}
/*************************************************
 *  시리얼라이저 활용!!
 * -------------------------------
 * 클래스(프로덕트)를 만들고        - 
 * - 번호( 코드 )                           -
 * - 이름(제품명)                          -
 * - 가격                                      -
 * - 제조사                                   -
 * -------------------------------
 *
 * - 프로덕트 객체 10개 생성
 *
 * - 저장
 *
 * - 읽기
 *
 * - 화면표시
 *
 * *********************************************/


 

반응형

'프로그램 > C# - Study' 카테고리의 다른 글

C# - Ex25Delegate 델리게이트  (1) 2010.10.13
C# - Ex24DirectoryAndFile  (0) 2010.10.13
11D - 예외처리(Exception)  (0) 2010.09.24
11D - ArrayList, Hashtable, ICollection, TheGeneric  (0) 2010.09.24
10D - 윈폼  (0) 2010.09.17
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유