"cannot convert from 'string' to 'System.IO.Stream'" while reading a file line by line using StreamReader

17,516

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());
    }
}
Share:
17,516
Titulum
Author by

Titulum

I 💕 💻

Updated on June 14, 2022

Comments

  • Titulum
    Titulum almost 2 years

    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?

    • Dan D
      Dan D over 6 years
      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?
    • D.J.
      D.J. over 6 years
      What framework do you use ?
    • D.J.
      D.J. over 6 years
      @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
    • Titulum
      Titulum over 6 years
      I'm new to c#, where can I see which framework I use?
    • Dan D
      Dan D over 6 years
      @d-j good point on different frameworks, In your project file *.csproj you should see a TargetFramework section.
  • Matthew Watson
    Matthew Watson over 6 years
    If you're using foreach then you should use File.ReadLines() to avoid having the entire file in memory.
  • benichka
    benichka over 6 years
    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 docs.microsoft.com/en-us/dotnet/standard/garbage-collection/‌​….