HOWTO · Csharp
C#에서 파일을 문자열로 읽기
파일의 모든 내용을 C#의 문자열 변수로 읽는 데 사용할 수있는 두 가지 주요 메서드 인 File.ReadAllText() 함수와 StreamReader.ReadToEnd() 함수가 있습니다.
이 자습서에서는 파일의 모든 내용을 C#의 문자열 변수로 읽는 방법에 대해 설명합니다.
C#에서File.ReadAllText()메서드를 사용하여 파일을 문자열로 읽기
File클래스는 C#의 파일과 상호 작용하는 많은 함수를 제공합니다. C#의 File.ReadAllText()메서드는 파일의 모든 내용을 읽습니다. File.ReadAllText()메소드는 파일의 경로를 인수로 취하고 지정된 파일의 내용을 문자열 변수로 리턴합니다. 다음 예제 코드를 참조하십시오.
using System;
using System.IO;
namespace read_file_to_string {
class Program {
static void Main(string[] args) {
string text = File.ReadAllText(@"C:\File\file.txt");
Console.WriteLine(text);
}
}
}
출력:
this is all the text in this file
위의 코드에서 우리는 C#의File.ReadAllText()메소드를 사용하여C:\File\경로에있는file.txt파일의 모든 내용을 문자열 변수text로 읽습니다.
C#에서StreamReader.ReadToEnd()메서드를 사용하여 파일을 문자열로 읽기
StreamReader클래스는 C#의 특정 인코딩을 사용하여 바이트 스트림에서 콘텐츠를 읽습니다. StreamReader.ReadToEnd()메소드는 C#에서 파일의 모든 내용을 읽는 데 사용됩니다. StreamReader.ReadToEnd()메소드는 지정된 파일의 내용을 문자열 변수로 리턴합니다. 다음 예제 코드를 참조하십시오.
using System;
using System.IO;
namespace read_file_to_string {
class Program {
static void Main(string[] args) {
StreamReader fileReader = new StreamReader(@"C:\File\file.txt");
string text = fileReader.ReadToEnd();
Console.WriteLine(text);
}
}
}
출력:
this is all the text in this file
위의 코드에서, C#의StreamReader.ReadToEnd()메소드를 사용하여C:\File\경로에있는file.txt파일의 모든 내용을 문자열 변수text로 읽어들입니다. 이 접근 방식은 이전 접근 방식보다 훨씬 빠릅니다.