繁体   English   中英

.net核心中StreamReader的更短解决方案

[英]A shorter solution to StreamReader in .net core

我有这个基本代码,用于在VS Code中使用带有Dotnet Core的StreamReader读取文件。 我可以在Visual Studio中使用.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
}

File类位于System.IO.FileSystem nuget包中

代码较少的类似结果? 删除你不必要的代码......这不会工作???

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM