"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());
}
}
Comments
-
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 over 6 yearsHave 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. over 6 yearsWhat framework do you use ?
-
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 over 6 yearsI'm new to c#, where can I see which framework I use?
-
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 over 6 yearsIf you're using
foreach
then you should useFile.ReadLines()
to avoid having the entire file in memory. -
benichka over 6 yearsWhat's the use of
counter
? Plus, for a type that implementsIDisposable
, you should use theusing
pattern (or put yourfile.Close()
in afinally
block): see docs.microsoft.com/en-us/dotnet/standard/garbage-collection/‌​….