programing

C#을 사용하여 파일 전체를 문자열로 읽는 방법

fastcode 2023. 4. 10. 22:22
반응형

C#을 사용하여 파일 전체를 문자열로 읽는 방법

텍스트 파일을 문자열 변수로 읽는 가장 빠른 방법은 무엇입니까?

개별 바이트를 읽고 문자열로 변환하는 등 여러 가지 방법으로 수행할 수 있다는 것을 알고 있습니다.코딩이 최소인 방법을 찾고 있었습니다.

어때?

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

File.ReadAllLines »StreamReader ReadLineC# 파일 처리에서

파일 읽기 비교

결과.StreamReader는 10,000개 이상의 행이 있는 큰 파일의 경우 훨씬 빠르지만 작은 파일의 경우 차이는 무시할 수 있습니다.항상 그렇듯이 다양한 크기의 파일을 계획하고 파일을 사용합니다.ReadAllLines는 퍼포먼스가 중요하지 않은 경우에만 사용할 수 있습니다.


StreamReader 어프로치

File.ReadAllText다른 사용자가 제안한 접근방식입니다.또한 퍼포먼스에 미치는 영향을 정량적으로 테스트한 적은 없지만, 보다 고속인 것 같습니다.File.ReadAllText(아래 비교 참조).그러나 성능 차이는 파일이 더 큰 경우에만 나타납니다.

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


파일 비교Readxx() vs StreamReader.읽기 xxx()

ILSpy를 통해 표시 코드를 보니 다음 사항을 알 수 있었습니다.File.ReadAllLines,File.ReadAllText.

  • File.ReadAllText - 용도StreamReader.ReadToEnd
  • File.ReadAllLines - 사용도StreamReader.ReadLine으로는, 「」, 「」의에 따른 추가의 하고 있습니다.List<string>읽기 행으로 반환하고 파일 끝까지 루프합니다.


따라서 두 가지 방법 모두 다음과 같은 편리한 기능을 기반으로 구축되어 있습니다.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;
}
string contents = System.IO.File.ReadAllText(path)

여기 MSDN 문서가 있습니다.

대부분의 경우( 벤치마크에 따라) 파일 전체를 문자열로 읽는 가장 빠른 방법은 다음과 같습니다.

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를 포함한 대부분의 경우 다른 기술에 견줘 승리했습니다.

파일을 확인합니다.ReadAllText() 메서드

몇 가지 중요한 의견:

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

이 메서드는 바이트 순서 마크의 존재에 근거해 파일의 부호화를 자동적으로 검출하려고 합니다.부호화 형식 UTF-8 및 UTF-32(빅엔디안과 리틀엔디안의 양쪽 모두)를 검출할 수 있습니다.

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

예외가 발생하더라도 이 메서드에 의해 파일 핸들이 닫힙니다.

string text = File.ReadAllText("Path");하나의 문자열 변수에 모든 텍스트를 포함할 수 있습니다.줄 한 줄씩 에는 이렇게할 수 .

string[] lines = File.ReadAllLines("Path");
System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();

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

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

@Cris 안해 。은 인용구입니다.MSDN Microsoft

방법론

이 실험에서는 두 가지 클래스가 비교됩니다.StreamReaderFileStream 지시됩니다.10K는 200K는 2개의 파일로 구성되어 있습니다.

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확실히 이 테스트에서 더 빠릅니다.시간이 50% 더 소요됩니다.StreamReader작은 파일을 읽습니다.대용량 파일의 경우 시간이 27% 더 소요되었습니다.

StreamReader줄.FileStream 좀 더 요.이것은 여분의 시간의 일부를 설명해 줄 것이다.

추천 사항

응용 프로그램이 데이터 섹션에서 수행해야 하는 작업에 따라 추가 처리 시간이 필요할 수 있습니다.이 "Data Columns"로 되어 있는 해 보겠습니다.CR/LF구분되어 있습니다.StreamReader 행에서 "Discription"을 찾습니다.CR/LF그 후 응용 프로그램은 특정 데이터 위치를 찾는 추가 해석을 수행합니다.(String ★★★★★★★★★★★★★★★★★★★★★★?SubString ) 、 「 」 。

편,는FileStream데이터를 청크로 읽으면 프로 액티브한 개발자는 스트림을 자신의 이익에 맞게 사용할 수 있는 논리를 조금 더 작성할 수 있습니다.필요한 데이터가 파일 내의 특정 위치에 있는 경우 메모리 사용량을 낮게 유지하므로 이 방법이 적합합니다.

FileStream속도를 위한 더 나은 메커니즘이지만 더 많은 논리가 필요합니다.

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

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

다음을 사용할 수 있습니다.

 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);
    }
}
string content = System.IO.File.ReadAllText( @"C:\file.txt" );

이렇게 쓸 수 있어요.

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 "";
        }
    }

이게 도움이 되길 바라.

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

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

ReadAllText와 StreamBuffer를 2Mb csv로 비교해보니 차이가 적었던 것 같은데 ReadAllText가 기능을 완료할 때까지의 시간에서 우위를 점하고 있는 것 같습니다.

파일 사용을 강력히 추천합니다.ReadLines(경로)는 StreamReader 또는 기타 파일 읽기 메서드와 비교됩니다.소형 파일 및 대형 파일 모두에 대한 자세한 성능 벤치마크를 아래에서 확인하십시오.이게 도움이 됐으면 좋겠어요.

파일 작업 읽기 결과:

작은 파일용(8줄만)

여기에 이미지 설명 입력

대용량 파일(128465줄)의 경우

여기에 이미지 설명 입력

재행 예:

public void ReadFileUsingReadLines()
{
    var contents = File.ReadLines(path);
}

주의: 벤치마크는 에서 실시합니다.NET 6 。

이 코멘트는 C#ReadAllText 함수의 도움을 받아 c++를 사용하여 winform의 텍스트파일 전체를 읽으려고 하는 사용자를 대상으로 합니다.

using namespace System::IO;

String filename = gcnew String(charfilename);
if(System::IO::File::Exists(filename))
{
     String ^ data = gcnew String(System::IO::File::RealAllText(filename)->Replace("\0", Environment::Newline));
     textBox1->Text = data;
}


언급URL : https://stackoverflow.com/questions/7387085/how-to-read-an-entire-file-to-a-string-using-c

반응형