如何使用 C# 将整个文件读取为字符串?

发布于 2024-12-04 04:03:32 字数 88 浏览 2 评论 0原文

将文本文件读入字符串变量的最快方法是什么?

我知道它可以通过多种方式完成,例如读取单个字节然后将它们转换为字符串。我一直在寻找一种编码最少的方法。

What is the quickest way to read a text file into a string variable?

I understand it can be done in several ways, such as read individual bytes and then convert those to string. I was looking for a method with minimal coding.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

月亮坠入山谷 2024-12-11 04:03:32

File.ReadAllText< 怎么样? /a>:

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

How about File.ReadAllText:

string contents = File.ReadAllText(@"C:\temp\test.txt");
另类 2024-12-11 04:03:32

来自 File.ReadAllLinesStreamReader ReadLine 的基准比较C# 文件处理

文件读取比较

结果。 StreamReader 对于 10,000 以上的大文件要快得多
行,但较小文件的差异可以忽略不计。一如既往,
计划不同大小的文件,并仅在以下情况下使用 File.ReadAllLines
性能并不重要。

StreamReader 方法

由于其他人已经建议了 File.ReadAllText 方法,您也可以尝试更快(我没有定量测试性能影响,但它似乎比 File.ReadAllText 更快(请参阅下面的比较))。仅当文件较大时,性能差异才会显现出来尽管。

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

File.Readxxx() 与 StreamReader.Readxxx() 的比较

通过 ILSpy 我发现了以下有关 File.ReadAllLinesFile.ReadAllText 的内容。

  • File.ReadAllText - 在内部使用 StreamReader.ReadToEnd
  • File.ReadAllLines - 还使用StreamReader.ReadLine 内部还有创建 List的额外开销,以作为读取行返回并循环直到文件末尾。

因此,这两种方法都是构建在 StreamReader 之上的额外便利层。该方法的指示性主体可以明显看出这一点。

ILSpy 反编译的 File.ReadAllText() 实现

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

A benchmark comparison of File.ReadAllLines vs StreamReader ReadLine from C# file handling

File Read Comparison

Results. StreamReader is much faster for large files with 10,000+
lines, but the difference for smaller files is negligible. As always,
plan for varying sizes of files, and use File.ReadAllLines only when
performance isn't critical.

StreamReader approach

As the File.ReadAllText approach has been suggested by others, you can also try the quicker (I have not tested quantitatively the performance impact, but it appears to be faster than File.ReadAllText (see comparison below)). The difference in performance will be visible only in case of larger files though.

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

Comparison of File.Readxxx() vs StreamReader.Readxxx()

Viewing the indicative code through ILSpy I have found the following about File.ReadAllLines, File.ReadAllText.

  • File.ReadAllText - Uses StreamReader.ReadToEnd internally
  • File.ReadAllLines - Also uses StreamReader.ReadLine internally with the additionally overhead of creating the List<string> to return as the read lines and looping till the end of file.

So both the methods are an additional layer of convenience built on top of StreamReader. This is evident by the indicative body of the method.

File.ReadAllText() implementation as decompiled by 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;
}
往日 2024-12-11 04:03:32
string contents = System.IO.File.ReadAllText(path)

这是 MSDN 文档

string contents = System.IO.File.ReadAllText(path)

Here's the MSDN documentation

静谧幽蓝 2024-12-11 04:03:32

对于那些觉得这些东西有趣又有趣的菜鸟来说,在大多数情况下将整个文件读入字符串的最快方法(根据这些基准)如下:

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。

For the noobs out there who find this stuff fun and interesting, the fastest way to read an entire file into a string in most cases (according to these benchmarks) is by the following:

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

However, the absolute fastest to read a text file overall appears to be the following:

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

Put up against several other techniques, it won out most of the time, including against the BufferedReader.

场罚期间 2024-12-11 04:03:32

看一下 File.ReadAllText() 方法

一些重要说明:

该方法打开一个文件,读取文件的每一行,然后添加
每一行作为字符串的一个元素。然后它关闭该文件。一条线
被定义为一个字符序列,后跟一个回车符
('\r')、换行符 ('\n') 或紧随其后的回车符
通过换行。结果字符串不包含终止符
回车和/或换行。

此方法尝试自动检测文件的编码
基于字节顺序标记的存在。编码格式 UTF-8 和
可以检测UTF-32(大端和小端)。

读取时使用ReadAllText(String, Encoding)方法重载
可能包含导入文本的文件,因为无法识别
字符可能无法正确读取。

此方法保证关闭文件句柄,即使
引发异常

Take a look at the File.ReadAllText() method

Some important remarks:

This method opens a file, reads each line of the file, and then adds
each line as an element of a string. It then closes the file. A line
is defined as a sequence of characters followed by a carriage return
('\r'), a line feed ('\n'), or a carriage return immediately followed
by a line feed. The resulting string does not contain the terminating
carriage return and/or line feed.

This method attempts to automatically detect the encoding of a file
based on the presence of byte order marks. Encoding formats UTF-8 and
UTF-32 (both big-endian and little-endian) can be detected.

Use the ReadAllText(String, Encoding) method overload when reading
files that might contain imported text, because unrecognized
characters may not be read correctly.

The file handle is guaranteed to be closed by this method, even if
exceptions are raised

二货你真萌 2024-12-11 04:03:32

string text = File.ReadAllText("Path"); 您将所有文本保存在一个字符串变量中。如果您需要单独的每一行,您可以使用:

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

string text = File.ReadAllText("Path"); you have all text in one string variable. If you need each line individually you can use this:

string[] lines = File.ReadAllLines("Path");
抚你发端 2024-12-11 04:03:32
System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
System.IO.StreamReader myFile =
   new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
傾城如夢未必闌珊 2024-12-11 04:03:32

如果您想从应用程序的 Bin 文件夹中选择文件,那么您可以尝试以下操作,并且不要忘记进行异常处理。

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

if you want to pick file from Bin folder of the application then you can try following and don't forget to do exception handling.

string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));
一腔孤↑勇 2024-12-11 04:03:32

@Cris 抱歉。这是引用 MSDN Microsoft

方法论

在这个实验中,将比较两个类。 StreamReaderFileStream 类将被引导从应用程序目录中完整读取两个 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% 的时间。

StreamReader 专门寻找换行符,而 FileStream 则不然。这将占用一些额外的时间。

建议

根据应用程序需要对数据部分执行的操作,可能会进行额外的解析,从而需要额外的处理时间。考虑这样一种情况:文件具有数据列,行以 CR/LF 分隔。 StreamReader 将沿着文本行查找 CR/LF,然后应用程序将进行额外的解析以查找数据的特定位置。 (您认为 String.SubString 没有代价吗?)

另一方面,FileStream 读取块中的数据,主动的开发人员可以编写更多的逻辑来使用流来为自己带来好处。如果所需的数据位于文件中的特定位置,那么这肯定是正确的方法,因为它可以降低内存使用量。

FileStream 是速度更好的机制,但需要更多逻辑。

@Cris sorry .This is quote MSDN Microsoft

Methodology

In this experiment, two classes will be compared. The StreamReader and the FileStream class will be directed to read two files of 10K and 200K in their entirety from the application directory.

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()

Result

enter image description here

FileStream is obviously faster in this test. It takes an additional 50% more time for StreamReader to read the small file. For the large file, it took an additional 27% of the time.

StreamReader is specifically looking for line breaks while FileStream does not. This will account for some of the extra time.

Recommendations

Depending on what the application needs to do with a section of data, there may be additional parsing that will require additional processing time. Consider a scenario where a file has columns of data and the rows are CR/LF delimited. The StreamReader would work down the line of text looking for the CR/LF, and then the application would do additional parsing looking for a specific location of data. (Did you think String. SubString comes without a price?)

On the other hand, the FileStream reads the data in chunks and a proactive developer could write a little more logic to use the stream to his benefit. If the needed data is in specific positions in the file, this is certainly the way to go as it keeps the memory usage down.

FileStream is the better mechanism for speed but will take more logic.

酒浓于脸红 2024-12-11 04:03:32

你可以使用:

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

you can use :

 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);
    }
}
怼怹恏 2024-12-11 04:03:32

用最少的 C# 代码实现最快的方法可能是这样的:

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

well the quickest way meaning with the least possible C# code is probably this one:

string readText = System.IO.File.ReadAllText(path);
温馨耳语 2024-12-11 04:03:32
string content = System.IO.File.ReadAllText( @"C:\file.txt" );
string content = System.IO.File.ReadAllText( @"C:\file.txt" );
难得心□动 2024-12-11 04:03:32

您可以这样使用

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

希望这会对您有所帮助。

You can use like this

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

Hope this will help you.

衣神在巴黎 2024-12-11 04:03:32

您也可以将文本文件中的文本读取到字符串中,如下所示

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

you can read a text from a text file in to string as follows also

string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
  str = str + sr.ReadLine();
}
避讳 2024-12-11 04:03:32

我对 2Mb csv 的 ReadAllText 和 StreamBuffer 进行了比较,似乎差异很小,但从完成功能所需的时间来看,ReadAllText 似乎占据了上风。

I made a comparison between a ReadAllText and StreamBuffer for a 2Mb csv and it seemed that the difference was quite small but ReadAllText seemed to take the upper hand from the times taken to complete functions.

无法言说的痛 2024-12-11 04:03:32

与 StreamReader 或任何其他文件读取方法相比,我强烈建议使用 File.ReadLines(path) 。请在下面找到小尺寸文件和大尺寸文件的详细性能基准。
我希望这会有所帮助。

文件操作读取结果:

对于小文件(仅8行)

在此处输入图像描述

对于较大的文件(128465 行)

<一个href="https://i.sstatic.net/RZvXd.png" rel="nofollow noreferrer">在此处输入图像描述

Readlines 示例:

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

注意:基准测试是在 .NET 6 中完成的。

I'd highly recommend using the File.ReadLines(path) compare to StreamReader or any other File reading methods. Please find below the detailed performance benchmark for both small-size file and large-size file.
I hope this would help.

File operations read result:

For small file (just 8 lines)

enter image description here

For larger file (128465 lines)

enter image description here

Readlines Example:

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

Note : Benchmark is done in .NET 6.

天荒地未老 2024-12-11 04:03:32

此评论适用于那些尝试在 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;
}


This comment is for those who are trying to read the complete text file in winform using c++ with the help of C# ReadAllText function

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


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文