C# I/O - System.IO.File 和 StreamWriter/StreamReader 之间的区别?
假设我只对处理文本文件感兴趣,那么与 StreamWriter 相比,System.IO.File 方法有哪些具体的优点或缺点?
是否涉及任何性能因素?基本区别是什么?在什么情况下应该使用其中的哪一个?
还有一个问题,如果我想将文件的内容读入字符串并对其运行 LINQ 查询,哪一个最好?
Assuming I am interested only in dealing with text files, what specific advantages or disadvantages does System.IO.File methods provide when compared to StreamWriter?
Are there any performance factors involved? What is the basic difference, and which of these should be used in what cases?
One more question, If i want to read the contents of a file into a string and run a LINQ query over it, which is best?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你指的是哪种方法?
例如,
WriteAllLines()
和WriteAllText
在幕后使用StreamWriter
。这是反射器输出:
Which method do you mean?
WriteAllLines()
andWriteAllText
for example usesStreamWriter
behind the scene.Here is the reflector output:
File 类中看似重复的方法背后有一些有趣的历史。它是在对 .NET 预发布版本进行可用性研究之后产生的。一群经验丰富的程序员编写代码来操作文件。他们以前从未接触过 .NET,只是有文档可供参考。成功率为0%。
是的,有区别。当您尝试读取千兆字节或更大的文件时,您就会发现这一点。这在 32 位版本上肯定会崩溃。逐行读取的 StreamReader 不存在这样的问题,它将使用很少的内存。这取决于程序的其余部分的功能,但尝试将便捷方法限制为不大于(例如,十几兆字节)的文件。
There's a bit of interesting history behind the seemingly duplicate methods in the File class. It came about after a usability study on a pre-release version of .NET. They asked a group of experienced programmers to write code to manipulate files. They were never exposed to .NET before and just had the docs to work from. The success rate was 0%.
Yes, there's a difference. You'll find out when you try to read a file that's a gigabyte or more. That's a guaranteed crash on the 32-bit version. No such problem with a StreamReader that reads line-by-line, it will use very little memory. It depends on what the rest of your program does but try to limit the convenience method to files no larger than, say, a dozen megabytes.
一般来说,我会使用
System.IO.File
而不是StreamReader
,因为前者主要是后者的方便包装。考虑File.OpenText
后面的代码:或
File.ReadAllLines
:您可以使用 Reflector 来查看其他一些方法,因为您可以看到它非常简单
用于读取 的内容文件,请查看:
Generally I'd go with
System.IO.File
overStreamReader
as the former is mostly a convenient wrapper for the latter. consider the code behindFile.OpenText
:Or
File.ReadAllLines
:You can use Reflector to check out some other methods, as you can see it's pretty straightforward
For reading the contents of the file, take a look at: