C #을 사용하여 전체 파일을 문자열로 읽는 방법은 무엇입니까?


답변:


373

방법에 대해 File.ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");

3
그러나 사용하기에 가장 적합한 기능은 아닙니다. 그의 대답에서 Devendra D. Chavan이 지적한 것처럼 StreamReader.ReadToEnd더 효율적입니다.
— Owen Blacker

40
@OwenBlacker "quickest"가 "최소 실행 시간"또는 "최소 이해 시간"을 의미하는지 여부에 따라 다릅니다.
— bonh

2
File.ReadAllText는 확실히 사용하기 가장 쉬운 것이지만 "Devendra D. Chavan"이 지적한 것처럼 가장 빠르지는 않습니다. 따라서 작은 파일을 읽는 경우 File.ReadAllText.it를 사용하는 것이 더 좋습니다. 실제로 텍스트 파일의 크기에 따라 다릅니다.
— Mana

서버에서 읽으 려면 이것을 확인 하십시오 . 희망이 누군가를 도울 것입니다.
— shaijut

1
@OwenBlacker-확실합니까? 벤치 마크 결과 StreamReader.ReadToEnd가보다 효율적 ReadAllLines입니다. 후자는 텍스트를 여러 줄로 나눕니다. 그러나 우리는 다른 방법에 대해 이야기하고 ReadAllText있습니다. 실제로 당신이 언급 한 답변 ReadAllText은 StreamReader.ReadToEnd내부적으로 전화 하는 것을 보여줍니다 .
— Ed Avis

170

의 벤치 마크 비교 File.ReadAllLines대 StreamReader ReadLine에서 C #을 파일 처리

파일 읽기 비교

결과. StreamReader는 10,000 줄 이상인 큰 파일의 경우 훨씬 빠르지 만 작은 파일의 차이는 무시할 수 있습니다. 항상 그렇듯이 다양한 크기의 파일을 계획하고 성능이 중요하지 않은 경우에만 File.ReadAllLines를 사용하십시오.


StreamReader 접근

는 AS File.ReadAllText접근 방식이 다른 사람에 의해 제안되었다, 당신은 또한 시도 할 수 있습니다 빨리 (내가 테스트하지 않았습니다 정량적 성능에 미치는 영향을하지만보다 빠른 것으로 보인다 File.ReadAllText(참조 비교 ) 아래). 차이 성능하지만 단지 큰 파일의 경우에 볼 수 있습니다.

string readContents;
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
     readContents = streamReader.ReadToEnd();
}


File.Readxxx ()와 StreamReader.Readxxx ()의 비교

를 통해 나타내는 코드보기 ILSpy 나는에 대해 다음과 같은 발견을 File.ReadAllLines, File.ReadAllText.

  • File.ReadAllText - StreamReader.ReadToEnd내부적으로 사용
  • File.ReadAllLines -또한 읽기 행으로 리턴하고 파일 끝까지 반복 StreamReader.ReadLine하도록 List<string>to 를 작성하는 오버 헤드가 추가로 내부적으로 사용 됩니다.


따라서 두 방법 모두 위에 구축 된 편의성 의 추가 계층 입니다 StreamReader. 이것은 방법의 지시체에 의해 명백하다.

File.ReadAllText() ILSpy에 의해 디 컴파일 된 구현

public static string ReadAllText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    return File.InternalReadAllText(path, Encoding.UTF8);
}   

private static string InternalReadAllText(string path, Encoding encoding)
{
    string result;
    using (StreamReader streamReader = new StreamReader(path, encoding))
    {
        result = streamReader.ReadToEnd();
    }
    return result;
}

2
당신도 비교 했습니까 File.ReadAllText??
— marc_s

2
ILSpy는 이것이 File.ReadAllText()단순히 랩퍼라고 제안합니다 StreamReader.ReadToEnd(). 추가 레이어가보다 약간 느리게 수행되어야한다고 생각합니다 StreamReader.ReadToEnd().
— Devendra D. Chavan

좋은 대답입니다. 아마도 해결책을 찾고있는 사람들에게는 약간의 설명이 있지만, 선택한 답변만큼 최소한 많은 표를받을 자격이 있습니다.
— Sandy Gifford

@Devendra D. Chavan : Offtopic이지만 ILSpy에 대한 참조 또는 문서는 어디서 찾을 수 있습니까?
— 바이러스 성자인

1
referencesource.microsoft.com/#mscorlib/system/io/… 에서 코드를 찾을 수도 있습니다 . 내가 얻지 못하는 ReadAllText것은 단지 래퍼 인 경우 속도에 큰 차이가있는 이유는 무엇 streamReader.ReadToEnd();입니까?
— Olivier Jacot-Descombes


6

File.ReadAllText () 메소드를 살펴보십시오.

몇 가지 중요한 말 :

이 메서드는 파일을 열고 파일의 각 줄을 읽은 다음 각 줄을 문자열의 요소로 추가합니다. 그런 다음 파일을 닫습니다. 줄은 일련의 문자 다음에 캐리지 리턴 ( '\ r'), 줄 바꿈 ( '\ n') 또는 캐리지 리턴 바로 다음에 줄 바꿈으로 정의됩니다. 결과 문자열에는 종료 캐리지 리턴 및 / 또는 줄 바꿈이 포함되지 않습니다.

이 방법은 바이트 순서 표시가 있는지에 따라 파일 인코딩을 자동으로 감지합니다. 인코딩 형식 UTF-8 및 UTF-32 (big-endian 및 little-endian)를 감지 할 수 있습니다.

인식 할 수없는 문자를 올바르게 읽을 수 없으므로 가져온 텍스트를 포함 할 수있는 파일을 읽을 때 ReadAllText (String, Encoding) 메서드 오버로드를 사용하십시오.

예외가 발생하더라도이 방법으로 파일 핸들을 닫을 수 있습니다.


6

string text = File.ReadAllText("Path");하나의 문자열 변수에 모든 텍스트가 있습니다. 각 줄이 개별적으로 필요한 경우 다음을 사용할 수 있습니다.

string[] lines = File.ReadAllLines("Path");

4
System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();

4

@Cris 죄송합니다. 이것은 인용입니다 MSDN Microsoft

방법론

이 실험에서는 두 클래스를 비교합니다. StreamReader와이 FileStream클래스는 응용 프로그램 디렉토리에서 전체가 10K와 200K의 두 파일을 읽을 이동합니다.

StreamReader (VB.NET)

sr = New StreamReader(strFileName)
Do
  line = sr.ReadLine()
Loop Until line Is Nothing
sr.Close()

FileStream (VB.NET)

Dim fs As FileStream
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Dim b(1024) As Byte
fs = File.OpenRead(strFileName)
Do While fs.Read(b, 0, b.Length) > 0
    temp.GetString(b, 0, b.Length)
Loop
fs.Close()

결과

여기에 이미지 설명을 입력하십시오

FileStream이 테스트에서 분명히 더 빠릅니다. StreamReader작은 파일을 읽는 데 50 % 더 시간이 걸립니다 . 큰 파일의 경우 27 %의 시간이 추가로 걸렸습니다.

StreamReaderFileStream그렇지 않으면 줄 바꿈을 찾고 있습니다. 이것은 여분의 시간 중 일부를 설명합니다.

추천

애플리케이션이 데이터 섹션과 관련하여 수행해야하는 작업에 따라 추가 처리 시간이 필요한 추가 구문 분석이있을 수 있습니다. 파일에 데이터 열이 있고 행이 CR/LF구분 되는 시나리오를 고려하십시오 . 는 StreamReader를 찾고 텍스트의 줄 아래로 일하는 것이 CR/LF, 다음 응용 프로그램은 데이터의 특정 위치를 찾고 추가 분석을 할 것입니다. (문자열이라고 생각 했습니까? SubString은 가격이 없습니까?)

반면에 FileStream, 데이터는 청크로 데이터를 읽으며 사전 개발자는 스트림을 사용하여 자신의 이익을 얻기 위해 조금 더 논리를 작성할 수 있습니다. 필요한 데이터가 파일의 특정 위치에있는 경우 이는 메모리 사용량을 줄이면서 진행할 방법입니다.

FileStream 속도를위한 더 나은 메커니즘이지만 더 많은 로직을 사용합니다.


그러나 어떻 StreamReader.ReadToEnd습니까?
— Owen Blacker

3

가능한 가장 적은 C # 코드를 사용하는 가장 빠른 방법은 아마도 다음과 같습니다.

string readText = System.IO.File.ReadAllText(path);

3

응용 프로그램의 Bin 폴더에서 파일을 선택하려면 다음을 시도하고 예외 처리를 잊지 마십시오.

string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));

3

당신이 사용할 수있는 :

 public static void ReadFileToEnd()
{
    try
    {
    //provide to reader your complete text file
        using (StreamReader sr = new StreamReader("TestFile.txt"))
        {
            String line = sr.ReadToEnd();
            Console.WriteLine(line);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}


2

이 물건의 재미와 흥미를 찾을 수있다 밖으로 noobs에 대한 가장 빠른 방법은 (대부분의 경우 문자열로 전체 파일 읽기 이 벤치 마크에 따라 다음과 같은 것입니다) :

using (StreamReader sr = File.OpenText(fileName))
{
        string s = sr.ReadToEnd();
}
//you then have to process the string

그러나 전체 텍스트 파일을 읽는 가장 빠른 속도는 다음과 같습니다.

using (StreamReader sr = File.OpenText(fileName))
{
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
               //do what you have to here
        }
}

BufferedReader를 포함하여 여러 가지 다른 기술에 대항 하여 대부분 승리했습니다.


의견은 늦었지만 여기와 링크 된 페이지에서 벤치 마크에 약간 혼란 스러웠습니다. 읽기 속도 만 테스트하고 전체 문자열에로드하지 않는 것으로 보입니다. 두 번째 코드 스 니펫은 한 번에 한 줄을 읽고 추가 작업을 수행하지 않으므로 "여기에 필요한 작업"에 데이터를 보유 할 문자열 빌더 또는 문자열이 있어야합니다. 이 시점에서 더 많은 데이터를 추가하는 데 사용 된 메모리는 테스트 결과를 변경합니다. 따라서 s는 일반적으로 고정 너비 파일을 가정 할 때 크기가 동일하므로 행 크기로 메모리가 설정되고 데이터를 새 메모리에 복사 할 필요가 없습니다.
— Charles Byrne

2

이렇게 사용할 수 있습니다

public static string ReadFileAndFetchStringInSingleLine(string file)
    {
        StringBuilder sb;
        try
        {
            sb = new StringBuilder();
            using (FileStream fs = File.Open(file, FileMode.Open))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (StreamReader sr = new StreamReader(bs))
                    {
                        string str;
                        while ((str = sr.ReadLine()) != null)
                        {
                            sb.Append(str);
                        }
                    }
                }
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            return "";
        }
    }

이것이 도움이되기를 바랍니다.


0

다음과 같이 텍스트 파일에서 문자열로 텍스트를 읽을 수 있습니다.

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}

0
public partial class Testfile : System.Web.UI.Page
{
    public delegate void DelegateWriteToDB(string Inputstring);
    protected void Page_Load(object sender, EventArgs e)
    {
        getcontent(@"C:\Working\Teradata\New folder");
    }

      private void SendDataToDB(string data)
    {
        //InsertIntoData
          //Provider=SQLNCLI10.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=kannan;Data Source=jaya;
        SqlConnection Conn = new SqlConnection("Data Source=aras;Initial Catalog=kannan;Integrated Security=true;");
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = Conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into test_file values('"+data+"')";
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
    }

      private void getcontent(string path)
      {
          string[] files;
          files = Directory.GetFiles(path, "*.txt");
          StringBuilder sbData = new StringBuilder();
          StringBuilder sbErrorData = new StringBuilder();
          Testfile df = new Testfile();
          DelegateWriteToDB objDelegate = new DelegateWriteToDB(df.SendDataToDB);
          //dt.Columns.Add("Data",Type.GetType("System.String"));


          foreach (string file in files)
          {
              using (StreamReader sr = new StreamReader(file))
              {
                  String line;
                  int linelength;
                  string space = string.Empty;

                  // Read and display lines from the file until the end of 
                  // the file is reached.
                  while ((line = sr.ReadLine()) != null)
                  {
                      linelength = line.Length;
                      switch (linelength)
                      {
                          case 5:
                              space = "     ";
                              break;

                      }
                      if (linelength == 5)
                      {
                          IAsyncResult ObjAsynch = objDelegate.BeginInvoke(line + space, null, null);
                      }
                      else if (linelength == 10)
                      {
                          IAsyncResult ObjAsynch = objDelegate.BeginInvoke(line , null, null);
                      }

                  }
              }
          }
      }
    }

0

2Mb csv에 대해 ReadAllText와 StreamBuffer를 비교 한 결과 차이가 매우 작지만 ReadAllText는 함수를 완료하는 데 걸리는 시간보다 우위에있는 것으로 보입니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.