텍스트 파일에서 읽는 방법(C# 프로그래밍 가이드)
이 예제에서는 System.IO.File 클래스의 정적 메서드 ReadAllText 및 ReadAllLines를 사용하여 텍스트 파일의 내용을 읽습니다.
StreamReader를 사용하는 예제는 텍스트 파일을 한 번에 한 줄씩 읽는 방법을 참조하세요.
참고
이 예제에 사용되는 파일은 텍스트 파일에 쓰는 방법 항목에서 생성되었습니다.
예제
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();
}
}
코드 컴파일
코드를 복사하고 C# 콘솔 애플리케이션에 붙여넣습니다.
텍스트 파일에 쓰는 방법의 텍스트 파일을 사용하지 않는 경우 ReadAllText
및 ReadAllLines
에 대한 인수를 사용자 컴퓨터의 적절한 경로 및 파일 이름으로 바꿉니다.
강력한 프로그래밍
다음 조건에서 예외가 발생합니다.
- 파일이 없거나 지정된 위치에 없는 경우. 경로와 파일 이름의 철자를 확인합니다.
.NET 보안
파일 이름을 사용하여 파일 내용을 확인하지 마세요. 예를 들어 myFile.cs
파일이 C# 소스 파일이 아닐 수도 있습니다.