"cannot convert from 'string' to 'System.IO.Stream'" 使用 StreamReader 逐行读取文件时

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

我正在按照在线教程在 C# 中逐行读取一个简单的文本文件,但出现此错误,我无法理解。

这是我的简单代码:

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

但这给了我一个错误:

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

This article on msdn 使用相同的代码并且可以正常工作,我做错了什么?

如果您想读取文件,最简单的方法是

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

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

你也可以这样做:

var path = "c:\mypath\to\my\file.txt";
using (var reader = new StreamReader(path))
{
    while (!reader.EndOfStream)
    {
        Console.WriteLine(reader.ReadLine());
    }
}

你可以这样做

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