'StreamWriter'에 해당되는 글 1건

  1. 2008.10.14 StreamWriter 클래스에 대한 고찰..

StreamWriter 클래스에 대한 고찰..

.Net 2008. 10. 14. 12:33 posted by 무명시인
http://msdn.microsoft.com/ko-kr/library/system.io.streamwriter(VS.80).aspx


.NET Framework 클래스 라이브러리
StreamWriter 클래스

TextWriter를 구현하여 특정 인코딩의 스트림에 문자를 씁니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class StreamWriter : TextWriter

StreamWriter는 특정 인코딩의 문자 출력을 위해 설계된 반면 Stream에서 파생된 클래스는 바이트 입력 및 출력을 위해 설계되었습니다.

다르게 지정되지 않은 경우 StreamWriter는 기본적으로 UTF8Encoding의 인스턴스를 사용합니다. UTF8Encoding의 이 인스턴스가 생성되어 Encoding.GetPreamble 메서드는 UTF-8로 작성된 유니코드 바이트 순서 표시를 반환합니다. 기존의 스트림에 추가하지 않는 경우 인코딩의 프리앰블이 스트림에 추가됩니다. 즉, StreamWriter로 만드는 텍스트 파일 맨 처음에는 세 개의 바이트 순서 표시가 나타납니다. UTF-8은 모든 유니코드 문자를 정확하게 처리하고 운영 체제의 지역화된 버전에 일관성 있는 결과를 제공합니다.

기본적으로 StreamWriter는 스레드로부터 안전하지 않습니다. 스레드로부터 안전한 래퍼에 대한 자세한 내용은 TextWriter.Synchronized를 참조하십시오.


 

.NET Framework 개발자 가이드
방법: 파일에 텍스트 쓰기

다음 코드 예제에서는 텍스트 파일에 텍스트를 쓰는 방법을 보여 줍니다.

첫 번째 예제에서는 기존 파일에 텍스트를 추가하는 방법을 보여 주고 두 번째 예제에서는 새 텍스트 파일을 만들고 이 파일에 문자열을 쓰는 방법을 보여 줍니다. 비슷한 기능을 WriteAllText 메서드에서 제공할 수도 있습니다.


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);
        }
    }
}