如何使用 C# 将整个文件读取为字符串?
将文本文件读入字符串变量的最快方法是什么?
我知道它可以通过多种方式完成,例如读取单个字节然后将它们转换为字符串。我一直在寻找一种编码最少的方法。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
File.ReadAllText
< 怎么样? /a>:How about
File.ReadAllText
:来自 的
File.ReadAllLines
与StreamReader ReadLine
的基准比较C# 文件处理StreamReader 方法
由于其他人已经建议了
File.ReadAllText
方法,您也可以尝试更快(我没有定量测试性能影响,但它似乎比File.ReadAllText
更快(请参阅下面的比较))。仅当文件较大时,性能差异才会显现出来尽管。File.Readxxx() 与 StreamReader.Readxxx() 的比较
通过 ILSpy 我发现了以下有关
File.ReadAllLines
、File.ReadAllText
的内容。File.ReadAllText
- 在内部使用StreamReader.ReadToEnd
File.ReadAllLines
- 还使用StreamReader.ReadLine 内部还有创建 List因此,这两种方法都是构建在 StreamReader 之上的额外便利层。该方法的指示性主体可以明显看出这一点。
ILSpy 反编译的
File.ReadAllText()
实现A benchmark comparison of
File.ReadAllLines
vsStreamReader ReadLine
from C# file handlingStreamReader 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 thanFile.ReadAllText
(see comparison below)). The difference in performance will be visible only in case of larger files though.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
- UsesStreamReader.ReadToEnd
internallyFile.ReadAllLines
- Also usesStreamReader.ReadLine
internally with the additionally overhead of creating theList<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这是 MSDN 文档
Here's the MSDN documentation
对于那些觉得这些东西有趣又有趣的菜鸟来说,在大多数情况下将整个文件读入字符串的最快方法(根据这些基准)如下:
但是,读取文本文件的绝对最快速度总体看来是如下:
对抗其他几种技术技术,它在大部分时间都获胜,包括对抗 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:
However, the absolute fastest to read a text file overall appears to be the following:
Put up against several other techniques, it won out most of the time, including against the BufferedReader.
看一下 File.ReadAllText() 方法
一些重要说明:
Take a look at the File.ReadAllText() method
Some important remarks:
string text = File.ReadAllText("Path");
您将所有文本保存在一个字符串变量中。如果您需要单独的每一行,您可以使用:string text = File.ReadAllText("Path");
you have all text in one string variable. If you need each line individually you can use this:如果您想从应用程序的 Bin 文件夹中选择文件,那么您可以尝试以下操作,并且不要忘记进行异常处理。
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.
@Cris 抱歉。这是引用
MSDN Microsoft
方法论
在这个实验中,将比较两个类。
StreamReader
和FileStream
类将被引导从应用程序目录中完整读取两个 10K 和 200K 的文件。结果
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 theFileStream
class will be directed to read two files of 10K and 200K in their entirety from the application directory.Result
FileStream
is obviously faster in this test. It takes an additional 50% more time forStreamReader
to read the small file. For the large file, it took an additional 27% of the time.StreamReader
is specifically looking for line breaks whileFileStream
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. TheStreamReader
would work down the line of text looking for theCR/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.你可以使用:
you can use :
用最少的 C# 代码实现最快的方法可能是这样的:
well the quickest way meaning with the least possible C# code is probably this one:
您可以这样使用
希望这会对您有所帮助。
You can use like this
Hope this will help you.
您也可以将文本文件中的文本读取到字符串中,如下所示
you can read a text from a text file in to string as follows also
我对 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.
与 StreamReader 或任何其他文件读取方法相比,我强烈建议使用 File.ReadLines(path) 。请在下面找到小尺寸文件和大尺寸文件的详细性能基准。
我希望这会有所帮助。
文件操作读取结果:
对于小文件(仅8行)
对于较大的文件(128465 行)
<一个href="https://i.sstatic.net/RZvXd.png" rel="nofollow noreferrer">
Readlines 示例:
注意:基准测试是在 .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)
For larger file (128465 lines)
Readlines Example:
Note : Benchmark is done in .NET 6.
此评论适用于那些尝试在 C# ReadAllText 函数的帮助下使用 C++ 读取 winform 中完整文本文件的人
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