我有这个基本代码,可以在 VS Code 中使用带有 Dotnet Core 的 StreamReader
读取文件。我可以在 Visual Studios 中使用 .net new StreamReader("file.json")
执行类似的操作,它看起来小巧紧凑。
我正在寻找 dotnet 核心中的另一个类,它可以用更少的代码实现类似的结果
using System;
using System.IO;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
StreamReader myReader = new StreamReader(new FileStream("project.json", FileMode.Open, FileAccess.Read));
string line = " ";
while(line != null)
{
line = myReader.ReadLine();
if(line != null)
{
Console.WriteLine(line);
}
}
myReader.Dispose();
}
}
}
最佳答案
在完整框架中,close方法与Dispose是多余的。 关闭流的推荐方式是通过using语句调用Dispose,以确保即使发生错误也能关闭流。
您可以使用 System.IO.File.OpenText() 直接创建 StreamReader。
在这里,您需要打开和关闭 StreamReader:
using (var myReader = File.OpenText("project.json"))
{
// do some stuff
}
文件类在 System.IO.FileSystem 中nuget包
关于c# - .net core 中 StreamReader 的更短解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057784/