A shorter solution to StreamReader in .net core

9.8k views Asked by At

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

There are 2 answers

0
Kalten On BEST ANSWER

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

0
JohnG On

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