[英]A shorter solution to StreamReader in .net core
I have this basic code to read a file with StreamReader
with Dotnet Core in VS Code. 我有这个基本代码,用于在VS Code中使用带有Dotnet Core的
StreamReader
读取文件。 I can do similar operation in Visual Studios with .net new StreamReader("file.json")
which looks small and compact. 我可以在Visual Studio中使用.net
new StreamReader("file.json")
进行类似的操作,它看起来小巧紧凑。
I am looking for another class in dotnet core which could achieve similar results with less code 我正在寻找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();
}
}
}
In the full framework, the close method is redundant with Dispose. 在完整的框架中,close方法对Dispose来说是多余的。 The recommended way to close a stream is to call Dispose through using statement in order to ensure closing stream even if an error happen.
关闭流的推荐方法是通过using语句调用Dispose,以确保即使发生错误也会关闭流。
You can use System.IO.File.OpenText() to directly create a StreamReader. 您可以使用System.IO.File.OpenText()直接创建StreamReader。
Here, just what you need to to open and close a StreamReader : 在这里,您只需打开和关闭StreamReader即可:
using (var myReader = File.OpenText("project.json"))
{
// do some stuff
}
The File class is in the System.IO.FileSystem nuget package File类位于System.IO.FileSystem nuget包中
Similar results with less code? 代码较少的类似结果? Remove your unnecessary code... Will this not work???
删除你不必要的代码......这不会工作???
try {
using (StreamReader myReader = File.OpenText("project.json")) {
string line = "";
while ((line = myReader.ReadLine()) != null) {
Console.WriteLine(line);
}
}
}
catch (Exception e) {
MessageBox.Show("FileRead Error: " + e.Message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.