A shorter solution to StreamReader in .net core

abhimanyuaryan picture abhimanyuaryan · Feb 5, 2017 · Viewed 8.2k times · Source

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

Answer

Kalten picture Kalten · Feb 5, 2017

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