방법: 텍스트 파일에 쓰기(C# 프로그래밍 가이드)
다음 코드 예제에서는 파일에 텍스트를 쓰는 여러 가지 방법을 보여 줍니다. 처음 두 예제에서는 File 클래스의 정적 메서드를 사용하여 전체 문자열 배열 또는 전체 문자열을 텍스트 파일에 씁니다. 세 번째 예제에서는 파일에 쓰기 전에 각 줄을 개별적으로 처리해야 할 경우 파일에 텍스트를 추가하는 방법을 보여 줍니다. 이 세 예제는 파일의 모든 기존 내용을 덮어씁니다. 네 번째 예제에서는 기존 파일에 텍스트를 추가하는 방법을 보여 줍니다.
예제
class WriteTextFile
{
static void Main()
{
// These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
// You can modify the path if necessary.
// Example #1: Write an array of strings to a file.
// Create a string array that consists of three lines.
string[] lines = { "First line", "Second line", "Third line" };
// WriteAllLines creates a file, writes a collection of strings to the file,
// and then closes the file.
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
// Example #2: Write one string to a text file.
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. ";
// WriteAllText creates a file, writes the specified string to the file,
// and then closes the file.
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);
// Example #3: Write only some strings in an array to a file.
// The using statement automatically closes the stream and calls
// IDisposable.Dispose on the stream object.
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);
}
}
}
// Example #4: Append new text to an existing file.
// The using statement automatically closes the stream and calls
// IDisposable.Dispose on the stream object.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
file.WriteLine("Fourth line");
}
}
}
//Output (to WriteLines.txt):
// First line
// Second line
// Third line
//Output (to WriteText.txt):
// A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.
//Output to WriteLines2.txt after Example #3:
// First line
// Third line
//Output to WriteLines2.txt after Example #4:
// First line
// Third line
// Fourth line
이 네 예제에서는 모두 파일에 문자열 리터럴을 쓰지만 대개는 Format 메서드를 사용합니다. 이 메서드는 필드에서 값을 오른쪽 또는 왼쪽 맞춤으로 정렬하고 안쪽 여백을 포함하거나 포함하지 않는 등 다양한 형식의 값을 쓰기 위한 많은 컨트롤을 포함합니다.
코드 컴파일
코드를 콘솔 응용 프로그램에 복사합니다.
"c:\testdir"을 컴퓨터의 실제 폴더 이름으로 바꾸거나 같은 이름의 폴더를 만듭니다.
강력한 프로그래밍
다음 조건에서 예외가 발생합니다.
파일이 있지만 읽기 전용인 경우
경로 이름이 너무 긴 경우
디스크가 꽉 찬 경우