프로그램(C# etc.)

c# 리스트박스에꺼 txt파일로 저장하는 코드 짜줘

질문폭격 2022. 12. 28. 17:54
using System.IO;

// ...

ListBox listBox1;

// ...

// 파일을 저장할 경로를 지정합니다.
string filePath = "C:\\example\\myfile.txt";

// 파일을 쓰기 전용으로 엽니다.
using (StreamWriter file = new StreamWriter(filePath))
{
    // 리스트박스에서 각 항목을 가져와 파일에 쓰기 작업을 수행합니다.
    foreach (string line in listBox1.Items)
    {
        file.WriteLine(line);
    }
}

 

txt 파일에서 읽어서 listbox에 넣는거 짜줘

using System.IO;

// ...

ListBox listBox1;

// ...

// 파일을 읽을 경로를 지정합니다.
string filePath = "C:\\example\\myfile.txt";

// 파일을 읽기 전용으로 엽니다.
using (StreamReader file = new StreamReader(filePath))
{
    // 파일을 한 줄씩 읽으며 반복합니다.
    string line;
    while ((line = file.ReadLine()) != null)
    {
        // 읽은 줄을 listBox1에 추가합니다.
        listBox1.Items.Add(line);
    }
}