방법: 파일에 텍스트 쓰기
.NET Framework 2.0
다음 코드 예제에서는 텍스트 파일에 텍스트를 쓰는 방법을 보여 줍니다.
첫 번째 예제에서는 기존 파일에 텍스트를 추가하는 방법을 보여 주고 두 번째 예제에서는 새 텍스트 파일을 만들고 이 파일에 문자열을 쓰는 방법을 보여 줍니다. 비슷한 기능을 WriteAllText 메서드에서 제공할 수도 있습니다.
참고 |
|---|
| Visual Basic 사용자는 파일 I/O의 My.Computer.FileSystem 개체에서 제공하는 메서드와 속성을 사용할 수 있습니다. 자세한 내용은 My.Computer.FileSystem 개체를 참조하십시오. |
예제
using System; using System.IO; class Test { public static void Main() { // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. using (StreamWriter sw = new StreamWriter("TestFile.txt")) { // Add some text to the file. sw.Write("This is the "); sw.WriteLine("header for the file."); sw.WriteLine("-------------------"); // Arbitrary objects can also be written to the file. sw.Write("The date is: "); sw.WriteLine(DateTime.Now); } } }
using System; using System.IO; public class TextToFile { private const string FILE_NAME = "MyFile.txt"; public static void Main(String[] args) { if (File.Exists(FILE_NAME)) { Console.WriteLine("{0} already exists.", FILE_NAME); return; } using (StreamWriter sw = File.CreateText(FILE_NAME)) { sw.WriteLine ("This is my file."); sw.WriteLine ("I can write ints {0} or floats {1}, and so on.", 1, 4.2); sw.Close(); } } }
참고