vb.net 写入文件时 FileStream 与 System.IO.File.WriteAllText

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17380506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:05:03  来源:igfitidea点击:

FileStream Vs System.IO.File.WriteAllText when writing to files

c#.netvb.net

提问by Flood Gravemind

I have seen many examples/ tutorials about VB.NET or C#.NET where the author is using a FileStreamto write/read from a file. My question is there any benefit to this method rather than using System.IO.File.Read/Write? Why are the majority of examples using FileStreamto when the same can be achieved using just a single line of code?

我看过很多关于 VB.NET 或 C#.NET 的示例/教程,其中作者使用 aFileStream来写入/读取文件。我的问题是这种方法比使用 有什么好处System.IO.File.Read/Write吗?FileStream当仅使用一行代码即可实现相同功能时,为什么大多数示例都使用to ?

回答by Mataniko

FileStreamgives you a little more control over writing files, which can be beneficial in certain cases. It also allows you to keep the file handle openand continuously write data without relinquishing control. Some use cases for a stream:

FileStream让您对写入文件有更多的控制,这在某些情况下是有益的。它还允许您保持文件句柄打开并在不放弃控制的情况下连续写入数据。流的一些用例:

  • Multiple inputs
  • Real time data from a memory/network stream.
  • 多路输入
  • 来自内存/网络流的实时数据。

System.IO.Filecontains wrappers around file operations for basic actions such as saving a file, reading a file to lines, etc. It's simply an abstraction over FileStream.

System.IO.File包含用于基本操作的文件操作的包装器,例如保存文件、读取文件到行等。它只是对FileStream.

From the .NET source code here is what WriteAllTextdoes internally:

从 .NET 源代码中,这里是WriteAllText内部执行的操作:

private static void InternalWriteAllText(string path,
    string contents, Encoding encoding)
{
    Contract.Requires(path != null);
    Contract.Requires(encoding != null);
    Contract.Requires(path.Length > 0);
    using (StreamWriter sw = new StreamWriter(path, false, encoding))
        sw.Write(contents);
}