Program Language/C#

[C#] 파일 쓰기

야곰야곰+책벌레 2023. 2. 17. 17:19
728x90
반응형

C#에서 파일을 쓰는 방법은 System.IO.File에 있는 Write 함수들을 이용하거나 StreamWriter를 사용하면 된다. 둘 다 같은 기능이지만, 하나에 파일에 반복해서 내용을 기입한다면 StreamWriter를 사용하는 것이 편리하다.

string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

string text = "A class is the most powerful data type in C#. Like a structure, " +
           "a class defines the data and behavior of the data type. ";

System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
{
    foreach (string line in lines)
    {
        // If the line doesn't contain the word 'Second', write the line to the file.
        if (!line.Contains("Second"))
        {
            file.WriteLine(line);
        }
    }
}

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
    file.WriteLine("Fourth line");
}

해당 코드를 실행시키면 지정한 폴더에 파일이 생성된다.

 

728x90
반응형