Abhimanyu Aryan Abhimanyu Aryan - 4 years ago 216
C# Question

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download