구조체와 클래스를 파일로 입력 및 출력을 한번에 하기위해서는 Serialize 와 Deserialize를 사용 하여야 합니다.

NET Framework 클래스 라이브러리

BinaryFormatter 생성자 자세히 알아보기

http://msdn.microsoft.com/library/KOR/cpref/html/frlrfSystemRuntimeSerializationFormattersBinaryBinaryFormatterClassctorTopic.asp?frame=true

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

클래스 저장하기

   //Class Save

저장하고자 하는 클래스
   Class1 c1 = new Class1("kojaedoo");

/*

using System;

namespace Test
{

[Serializable()] <----꼭 해주어야 합니당
public class Class1
{

  string name;
  public Class1(string name)
  {
   //
   // TODO: 여기에 생성자 논리를 추가합니다.
   //
   this.name = name;
  }
}

}

*/
   BinaryFormatter serializer = new BinaryFormatter(); 

저장하고자 하는 파일네임

   Stream stream = File.Open("data.txt", FileMode.Create);

   serializer.Serialize(stream ,c1);
   stream.Close();

   c1 = null;

클래스 불러오기

   //Class Open
   stream = File.Open( "data.txt", FileMode.Open  );

   BinaryFormatter formatter = new BinaryFormatter();

   Class1 c3 = (Class1)formatter.Deserialize( stream );

   MessageBox.Show( "data.txt에서 가지고 온값::::"+c3.Name );

ex)

        [Serializable]

        public class st_Option

        {

            public int[]        nData=new int [10];

            public double[] dblData=new double [10];

            public string[] szData=new string [10];

        }

선언은 위와 같이 해주시면 되고,

using System.Runtime.Serialization.Formatters.Binary;

            // Serialize하는 경우

            st_Option op=new st_Option ();

            DateTime time=DateTime.Now;

            op.szData[0]=time.Ticks.ToString();

            FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(fs, op); 

            fs.Close();

            // Deserialize 하는 경우

            FileStream fs = new FileStream("DataFile.dat", FileMode.Open);

            BinaryFormatter bf = new BinaryFormatter();

            Define.st_Option op=null;

            op=(Define.st_Option)bf.Deserialize(fs);

            fs.Close();

            //op.nData[0] 에 들어간 값 확인

            MessageBox.Show(op.nData[0].ToString());

출처 : http://www.devpia.com/Forum/BoardView.aspx?no=52583&ref=52583&page=1&forumname=CSHARP_QA&stype=&KeyW=%b1%b8%c1%b6%c3%bc&KeyR=title

+ Recent posts