简体   繁体   中英

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. I can do similar operation in Visual Studios with .net new StreamReader("file.json") which looks small and compact.

I am looking for another class in dotnet core which could achieve similar results with less code

 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. 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.

You can use System.IO.File.OpenText() to directly create a StreamReader.

Here, just what you need to to open and close a StreamReader :

using (var myReader = File.OpenText("project.json"))
{
    // do some stuff
}

The File class is in the System.IO.FileSystem nuget package

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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