2

I am following a tutorial online to read a simple text file line by line in c# but I get this error that I can't wrap my head around.

This is my simple code:

StreamReader reader = new StreamReader("hello.txt");

but this gives me an error:

Argument 1: cannot convert from 'string' to 'System.IO.Stream'

This article on msdn uses the same code and there it works, what am I doing wrong?

Titulum
  • 9,928
  • 11
  • 41
  • 79
  • 1
    Have your tried a clean and rebuild? The constructor with a string parameter is definitely valid. I'm assuming this error is at compile-time correct? – Dan D Sep 25 '17 at 12:20
  • What framework do you use ? – D.J. Sep 25 '17 at 13:46
  • @DanD hard to say without knowing the used framework, this constructor for example is not included in netStandard<2.0, also this is missing in netCore<2.0 – D.J. Sep 25 '17 at 13:52
  • I'm new to c#, where can I see which framework I use? – Titulum Sep 25 '17 at 15:10
  • @d-j good point on different frameworks, In your project file *.csproj you should see a TargetFramework section. – Dan D Sep 25 '17 at 18:10

2 Answers2

4

If you want to read a file the easiest way is

var path = "c:\\mypath\\to\\my\\file.txt";
var lines = File.ReadAllLines(path);

foreach (var line in lines)
{
    Console.WriteLine(line);
}

You can also do it like this:

var path = "c:\\mypath\\to\\my\\file.txt";
using (var reader = new StreamReader(path))
{
    while (!reader.EndOfStream)
    {
        Console.WriteLine(reader.ReadLine());
    }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Simon Price
  • 3,011
  • 3
  • 34
  • 98
0

You can do like this

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\hello.txt");
 while((line = file.ReadLine()) != null)
{
     Console.WriteLine (line);
     counter++;
}

file.Close();
Andre.Santarosa
  • 1,150
  • 1
  • 9
  • 22
  • 2
    What's the use of `counter`? Plus, for a type that implements `IDisposable`, you should use the `using` pattern (or put your `file.Close()` in a `finally` block): see https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects. – benichka Sep 25 '17 at 12:53