본문 바로가기
.Net/C#

C# List Generic Struct/txt Save 리스트 배열 구조체 텍스트 저장

by Cum 2022. 9. 29.
728x90
반응형

C#에서 Generic List를 텍스트 또는 구조체로 저장하는 방법

 

1. txt 저장

List<string> val = new List<string>();

private void test()
{
    string time = DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss");
    StreamWriter sw = new StreamWriter(time + ".txt");
    for (int i = 0; i < val.Count; i++)
    {
        sw.Write(val[i]);
    }
    sw.Close();
}

위 방법으로 저장 시 for문이 돌기 때문에 배열 개수가 많을수록 시간이 많이 걸림

 

2. 구조체 저장

public struct DataList
{
    public string data;
}

DataList dl = new DataList();
List<DataList> val = new List<DataList>(); //write
List<DataList> val2 = new List<DataList>(); //read

private void test()
{
    using (FileStream fs = new FileStream("Val.dat", FileMode.Create))//구조체 저장
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, val);
    }

    using (FileStream fs = new FileStream("Val.dat", FileMode.Open))//구조체 불러오기
    {
        BinaryFormatter bf = new BinaryFormatter();
        val2 = (List<DataList>)bf.Deserialize(fs);
    }
}

구조체로 저장하게 되면 한 번에 저장되기 때문에 배열 개수에 구애받지 않음

728x90
반응형

댓글