Visual C#으로 텍스트 파일 읽기 및 쓰기

이 문서에서는 Visual C#을 사용하여 텍스트 파일을 읽고 쓰는 방법을 설명합니다.

원래 제품 버전: Visual Studio
원본 KB 번호: 816149

요약

이 문서의 텍스트 파일 읽기 섹션에서는 StreamReader 클래스를 사용하여 텍스트 파일을 읽는 방법을 설명합니다. 텍스트 파일 쓰기(예제 1)텍스트 파일 쓰기(예제 2) 섹션에서는 StreamWriter 클래스를 사용하여 파일에 텍스트를 쓰는 방법을 설명합니다.

텍스트 파일 읽기

다음은 StreamReader 클래스를 사용하여 텍스트 파일을 열고 읽고 닫는 코드입니다. 텍스트 파일의 경로를 StreamReader 생성자에 전달하여 파일을 자동으로 열 수 있습니다. ReadLine 메서드는 각 텍스트 줄을 읽으며 파일 포인터를 다음 줄로 조금씩 올려 줍니다. ReadLine 메서드가 파일의 끝에 도달하면 null 참조가 반환됩니다. 자세한 내용은 StreamReader Class를 참조하세요.

  1. 메모장에서 샘플 텍스트 파일을 만듭니다. 다음 단계를 따릅니다.

    1. hello world 텍스트를 메모장에 붙여넣기 합니다.
    2. 파일을 Sample.txt로 저장합니다.
  2. Microsoft Visual Studio를 시작합니다.

  3. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 선택합니다.

  4. 프로젝트 유형에서 Visual C# 프로젝트를 선택한 다음 템플릿에서 콘솔 응용 프로그램을 선택합니다.

  5. Class1.cs 파일의 시작 부분에 다음 코드를 추가합니다.

    using System.IO;
    
  6. Main 메서드에 다음 코드를 추가합니다.

    String line;
    try
    {
        //Pass the file path and file name to the StreamReader constructor
        StreamReader sr = new StreamReader("C:\\Sample.txt");
        //Read the first line of text
        line = sr.ReadLine();
        //Continue to read until you reach end of file
        while (line != null)
        {
            //write the line to console window
            Console.WriteLine(line);
            //Read the next line
            line = sr.ReadLine();
        }
        //close the file
        sr.Close();
        Console.ReadLine();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  7. 디버그 메뉴에서 시작을 선택하여 컴파일하고 응용 프로그램을 실행합니다. ENTER를 누르고 콘솔 창을 닫습니다. 콘솔 창에 Sample.txt 파일의 내용이 표시됩니다.

    Hello world
    

텍스트 파일(예제 1) 쓰기

다음은 StreamWriter 클래스를 사용하여 텍스트 파일을 열고 쓰고 닫는 코드입니다. StreamReader 클래스와 마찬가지로 텍스트 파일의 경로를 StreamWriter 생성자에 전달하여 파일을 자동으로 열 수 있습니다. WriteLine 메서드는 텍스트 파일에 완전한 한 줄의 텍스트를 작성합니다.

  1. Visual Studio를 시작합니다.

  2. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 선택합니다.

  3. 프로젝트 유형에서 Visual C# 프로젝트를 선택한 다음 템플릿에서 콘솔 응용 프로그램을 선택합니다.

  4. Class1.cs 파일의 시작 부분에 다음 코드를 추가합니다.

    using System.IO;
    
  5. Main 메서드에 다음 코드를 추가합니다.

    try
    {
        //Pass the filepath and filename to the StreamWriter Constructor
        StreamWriter sw = new StreamWriter("C:\\Test.txt");
        //Write a line of text
        sw.WriteLine("Hello World!!");
        //Write a second line of text
        sw.WriteLine("From the StreamWriter class");
        //Close the file
        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  6. 디버그 메뉴에서 시작을 선택하여 컴파일하고 응용 프로그램을 실행합니다. 이 코드는 C 드라이브에 Test.txt 파일을 만듭니다. 메모장과 같은 텍스트 편집기에서 Test.txt 파일을 엽니다. Test.txt 파일에는 두 줄의 텍스트가 포함되어 있습니다.

    Hello World!!
    From the StreamWriter class
    

텍스트 파일(예제 2) 쓰기

다음은 StreamWriter 클래스를 사용하여 텍스트 파일을 열고 쓰고 닫는 코드입니다. 이 코드는 이전 예제와 달리 생성자에 두 개의 추가 매개 변수를 전달합니다. 첫 번째 매개 변수는 파일의 파일 경로와 파일 이름입니다. 두 번째 매개 변수 true은(는) 파일이 추가 모드로 열리게 지정합니다. false을(를) 두 번째 매개 변수로 지정하면 코드를 실행할 때마다 파일의 내용이 덮어 쓰입니다. 세 번째 매개 변수가 Unicode을(를) 지정하므로 StreamWriter은(는) 파일을 유니코드 형식으로 인코딩합니다. 세 번째 매개 변수에 대해 다음 인코딩 메서드를 지정할 수도 있습니다.

  • ASC11
  • 유니코드
  • UTF7
  • UTF8

Write 메서드가 캐리지 리턴이나 줄 피드(CR/LF) 문자 조합을 자동으로 포함하지 않는다는 것을 제외하면 Write 메서드는 WriteLine 메서드와 비슷합니다. 한 번에 한 문자씩 작성하려는 경우 유용합니다.

  1. Visual Studio를 시작합니다.

  2. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 클릭합니다.

  3. 프로젝트 유형에서 Visual C# 프로젝트를 선택한 다음 템플릿에서 콘솔 응용 프로그램을 선택합니다.

  4. Class1.cs 파일의 시작 부분에 다음 코드를 추가합니다.

    using System.IO;
    using System.Text;
    
  5. Main 메서드에 다음 코드를 추가합니다.

    Int64 x;
    try
    {
        //Open the File
        StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
    
        //Write out the numbers 1 to 10 on the same line.
        for(x=0; x < 10; x++)
        {
        sw.Write(x);
        }
    
        //close the file
        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  6. 디버그 메뉴에서 시작을 선택하여 컴파일하고 응용 프로그램을 실행합니다. 이 코드는 C 드라이브에 Test1.txt 파일을 만듭니다. 메모장과 같은 텍스트 편집기에서 Test1.txt 파일을 엽니다. Test1.txt에는 0123456789라는 텍스트 한 줄이 포함되어 있습니다.

텍스트 파일을 읽는 방법에 대한 전체 코드 목록

//Read a Text File
using System;
using System.IO;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            String line;
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("C:\\Sample.txt");
                //Read the first line of text
                line = sr.ReadLine();
                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the line to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }
                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

텍스트 파일을 작성하는 방법에 대한 전체 코드 목록(버전 1)

//Write a text file - Version-1
using System;
using System.IO;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                //Pass the filepath and filename to the StreamWriter Constructor
                StreamWriter sw = new StreamWriter("C:\\Test.txt");
                //Write a line of text
                sw.WriteLine("Hello World!!");
                //Write a second line of text
                sw.WriteLine("From the StreamWriter class");
                //Close the file
                sw.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

텍스트 파일을 작성하는 방법에 대한 전체 코드 목록(버전 2)

//Write a text file - Version 2
using System;
using System.IO;
using System.Text;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            Int64 x;
            try
            {
                //Open the File
                StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
                //Writeout the numbers 1 to 10 on the same line.
                for(x=0; x < 10; x++)
                {
                    sw.Write(x);
                }
                //close the file
                sw.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

문제 해결

모든 파일 조작의 경우 오류 및 예외를 처리하기 위해 코드를 try-catch-finally 블록 안에 래핑하는 것이 좋습니다. 특히 파일이 무기한 잠겨 있지 않은 경우 마지막 블록의 파일에 대한 핸들을 해제할 수 있습니다. 일부 가능한 오류에는 존재하지 않는 파일이나 이미 사용 중이던 파일이 포함됩니다.