방법: 텍스트 파일에서 읽기(C# 프로그래밍 가이드)

이 예제에서는 System.IO.File 클래스의 정적 메서드 ReadAllText 및 ReadAllLines를 사용하여 텍스트 파일의 내용을 읽습니다.

StreamReader를 사용하는 예제는 방법: 텍스트 파일을 한 번에 한 줄씩 읽기를 참조하세요.

참고

이 예제에 사용되는 파일은 방법: 텍스트 파일에 쓰기 항목에서 생성되었습니다.

예제

C#
class ReadFromFile
{
    static void Main()
    {
        // The files used in this example are created in the topic
        // How to: Write to a Text File. You can change the path and
        // file name to substitute text files of your own.

        // Example #1
        // Read the file as one string.
        string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

        // Example #2
        // Read each line of the file into a string array. Each element
        // of the array is one line of the file.
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}


'Knowledge' 카테고리의 다른 글

Aborting Thread Vs Cancelling Task  (0) 2018.04.18
Task And Thread In C#  (0) 2018.04.18
[SQLite3] 튜토리얼 사이트  (0) 2018.04.15
[SQLite3] DataType  (0) 2018.04.15
[WUP] SQLite 관련 Tutorial  (0) 2018.04.14

+ Recent posts