다음을 통해 공유


StreamReader 클래스

특정 인코딩의 바이트 스트림에서 문자를 읽는 TextReader를 구현합니다.

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

구문

‘선언
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class StreamReader
    Inherits TextReader
‘사용 방법
Dim instance As StreamReader
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class StreamReader : TextReader
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class StreamReader : public TextReader
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class StreamReader extends TextReader
SerializableAttribute 
ComVisibleAttribute(true) 
public class StreamReader extends TextReader

설명

StreamReader는 특정 인코딩으로 입력된 문자를 읽도록 설계된 반면 Stream 클래스는 입력 및 출력된 바이트를 읽도록 설계되었습니다. StreamReader를 사용하여 표준 텍스트 파일에서 정보 줄을 읽습니다.

별도로 지정하지 않으면 StreamReader는 기본적으로 현재 시스템의 ANSI 코드 페이지 대신 UTF-8 인코딩으로 지정됩니다. UTF-8은 유니코드 문자를 정확하게 처리하고 운영 체제의 지역화된 버전에 대한 일관성 있는 결과를 제공합니다.

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

Write(Char[],Int32,Int32)Read(Char[],Int32,Int32) 메서드는 count 매개 변수에 지정된 문자 수를 읽고 씁니다. 이들은 count 매개 변수에 의해 지정된 바이트 수를 읽고 쓰는 BufferedStream.ReadBufferedStream.Write와는 구별되어야 합니다. 바이트 배열 요소의 정수를 읽고 쓰는 경우에는 BufferedStream 메서드를 사용합니다.

참고

Stream에서 읽어올 때 스트림의 내부 버퍼와 동일한 크기인 버퍼를 사용하는 것이 보다 효율적입니다.

이 클래스 사용에 대한 예제를 보려면 예제 단원을 참조하십시오. 다음 표에서는 일반적인 예 또는 관련된 I/O 작업의 예를 보여 줍니다.

수행 작업

참조 항목

텍스트 파일을 만듭니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에 씁니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에서 읽습니다.

방법: 파일의 텍스트 읽기

파일에 텍스트를 추가합니다.

방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText

파일 크기를 가져옵니다.

FileInfo.Length

파일 특성을 가져옵니다.

File.GetAttributes

파일의 특성을 설정합니다.

File.SetAttributes

파일이 있는지 여부를 확인합니다.

File.Exists

이진 파일에서 읽습니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

이진 파일에 씁니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

예제

다음 코드 예제에서는 StreamReader 개체를 사용하여 파일에서 텍스트를 읽습니다.

Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        Try
            ' Create an instance of StreamReader to read from a file.
            Dim sr As StreamReader = New StreamReader("TestFile.txt")
            Dim line As String
            ' Read and display the lines from the file until the end 
            ' of the file is reached.
            Do
                line = sr.ReadLine()
                Console.WriteLine(Line)
            Loop Until line Is Nothing
            sr.Close()
        Catch E As Exception
            ' Let the user know what went wrong.
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(E.Message)
        End Try
    End Sub
End Class
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
using namespace System;
using namespace System::IO;
int main()
{
   try
   {
      // Create an instance of StreamReader to read from a file.
      // The using statement also closes the StreamReader.
      StreamReader^ sr = gcnew StreamReader( "TestFile.txt" );
      try
      {
         String^ line;
         
         // Read and display lines from the file until the end of 
         // the file is reached.
         while ( line = sr->ReadLine() )
         {
            Console::WriteLine( line );
         }
      }
      finally
      {
         if ( sr )
            delete (IDisposable^)sr;
      }
   }
   catch ( Exception^ e ) 
   {
      // Let the user know what went wrong.
      Console::WriteLine( "The file could not be read:" );
      Console::WriteLine( e->Message );
   }
}
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        try {            
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            StreamReader sr = new StreamReader("TestFile.txt");
            try {
                String line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) {
                    Console.WriteLine(line);
                }
            }
            finally {
                sr.Dispose();
            }            
        }
        catch (System.Exception e) {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.get_Message());
        }
    } //main
} //Test

상속 계층 구조

System.Object
   System.MarshalByRefObject
     System.IO.TextReader
      System.IO.StreamReader

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

StreamReader 멤버
System.IO 네임스페이스
Encoding
Stream 클래스
StreamWriter

기타 리소스

파일 및 스트림 I/O
방법: 파일의 텍스트 읽기
방법: 파일에 텍스트 쓰기
기본 파일 I/O
방법: 새로 만든 데이터 파일 읽기 및 쓰기