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
반응형
'.Net > C#' 카테고리의 다른 글
C# DateTime Ticks to Seconds TimeSpan 활용 사용한 시간 구하기 (0) | 2022.10.12 |
---|---|
C# WPF 다른 스레드가 이 개체를 소유하고 있어 호출 스레드가 해당 개체에 액세스할 수 없습니다. (0) | 2022.10.05 |
C# 텍스트 파일(txt) 쓰기 읽기 (0) | 2022.09.27 |
댓글