스트림, 직렬화( 파일 입출력을 쉽게하기위한 ) Serialization.

파일 스트림 이란? 파일을 읽고 쓴다.

스트림: 파일,네트워크 등에서 데이터를 *바이트 단위로 읽고 쓰는 클래스.


Stream Class는 상위 기본 클래스이다.

상속클래스에는 FileStream, MemoryStream, NetWorkStream, SqlFileStream 등이 있다.

using System.IO 선언후 사용가능.

System.Object.IO.Stream.FileStream: *byte[] 배열로 데이터를 읽거나 저장한다. (형변환 요구됨);




StreamWriter //텍스트 읽고쓰고 (쓰기용도만가능)

BinaryWriter // 0,1이지만 임의의 데이터형을 읽고쓸때.


public FileStream(

string path, //경로

FileMode mode, //생성,기존파일 열것이냐

FileAccess access //읽을거냐 쓸거냐

)


FileMode (Append,Create, CreateNewOpen, OpenOrCreate, Truncate)

FileAccess(Read,Write)

파일스트림생성한후 이것을 StreamRead/Wrtier에게 넘긴다.

텍스트 파일특징: 1바이트, 아스키코드 기반, c#에서는 유니코드로 인코딩된다.


*using 문: sw.close()를 자동적으로 한다.

using (StreamWriter sw = new StreamWriter(new FileStream("test2.txt", FileMode.Create)))

{

    sw.WriteLine(234234324);

    sw.WriteLine("DFgdfg");

    sw.Close();

}

보통 new FileStream("test2.txt", FileMode.Create) -> "test2.txt" 로 축약해서사용한다.



string 데이터 분리.

 string str = "국어: 90.6 영어: 100 수학: 70";

 string[] str_Element = str.Split(new char[] { ' ' });

 float kor = float.Parse(str_Element[1]);

Math.Round(average) ; 반올림한값을 리턴한다.


이진 파일 읽기와 쓰기 (우리가 지정한 형태의 변수로 읽고쓴다)

BinaryWriter/BinaryReader  네트워크에서 많이사용

메소드(ReadBoolean(),ReadByte(), ReadSingle() float)

bw.Write()

BinaryReader(Stream Encoding,Boolean)

구조체를 이진파일로 읽는 예

 int VAR1; 

using (BinaryReader bw = new BinaryReader(File.Open("test.dat", FileMode.Open)))

 {

     VAR1 = bw.ReadInt32();

 }

 Console.WriteLine(" {0}", VAR1);


*직렬화: 구조체,클래스 저장 읽기

FileStream, BinaryFormatter

using System.Runtime.Serialization.Formatters.Binary;

Deserialzie: 읽어서 다시 구조체,클래스에 넣기 반환형 object

 

역직렬화: 직렬화 대상에서 제외.

읽고싶지않은 데이터 제외. [NonSerialized] 키워드사용


 [Serializable]

    struct DATA

    {

        public int var1;

        public float var2;

        //[NonSerialized]

        public string str1;


        public DATA(int a, string b,float c)

        {

            var1 = a;

            var2 = c;

            str1 = b;

        }

    }


      DATA[] Data = new DATA[2];


            Data[0].var1 = 1;

            Data[0].var2 = 1.23f;

            Data[0].str1 = "dfg";

            Data[1].var1 = 2;

            Data[1].var2 = 3.41f;

            Data[1].str1 = "Wrert";


            using (FileStream fs1 = new FileStream("test.dat", FileMode.Create))

            {

                BinaryFormatter bf = new BinaryFormatter();

                bf.Serialize(fs1, Data);

            }


            DATA[] ResultData;

            using (FileStream fs2 = new FileStream("test.dat", FileMode.Open))

            {

                BinaryFormatter bf2 = new BinaryFormatter();

                ResultData = (DATA[])bf2.Deserialize(fs2);

            }

            for (int i = 0; i < 2; ++i)

            {

                Console.WriteLine("{0} {1} {2}", ResultData[i].var1, ResultData[i].var2,

                    ResultData[i].str1);

            }


컬렉션의 직렬화.

컬렉션(리스트, , 비트 배열, 해시 테이블 사전과 같은 다양한 개체

컬렉션을 정의하는 인터페이스와 클래스가 포함되어 있습니다.) 제네릭(c++템플릿):

같은 데이터형의 임의의 메모리 또는 연속적인 메모리를 다룰수 있도록 하는 클래스

ArrayList, List<T>, 제네릭을 이용한 직렬화.


          List<DATA> ResultList;

            List<DATA> DataList = new List<DATA>();

            DataList.Add(new DATA(7,"test1"));

            DataList.Add(new DATA(12,"test2"));

 


            using (FileStream fs1 = new FileStream("test.dat", FileMode.Create))

            {

                BinaryFormatter bf = new BinaryFormatter();

                bf.Serialize(fs1, DataList);

            }

            using (FileStream fs1 = new FileStream("test.dat", FileMode.Open))

            {

                BinaryFormatter bf = new BinaryFormatter();

                ResultList = (List<DATA>)bf.Deserialize(fs1);

            }


            for (int i = 0; i<2; ++i)

            {

                Console.WriteLine("{0} {1}", DataList[i].var1, DataList[i].var2);

            }


파일 입출력 정리:







'C#, ASP.NET, CORE, MVC' 카테고리의 다른 글

[펌] 가비지 컬렉터 (Garbage Collector) 의 원리, 동작 메커니즘  (2) 2018.07.19
5강. 클래스 OOP  (1) 2018.07.19
3강. 배열  (2) 2018.07.19
2강. 데이터형,기본문법  (0) 2018.07.18
[C#] 박싱 & 언박싱  (0) 2018.07.18

+ Recent posts