C# 使用StreamReader逐行读取文件时,“无法从‘string’转换为‘System.IO.Stream’”
我正在网上学习一个教程,用c语言逐行阅读一个简单的文本文件,但是我遇到了一个错误,我无法理解这个错误 这是我的简单代码:C# 使用StreamReader逐行读取文件时,“无法从‘string’转换为‘System.IO.Stream’”,c#,.net,streamreader,C#,.net,Streamreader,我正在网上学习一个教程,用c语言逐行阅读一个简单的文本文件,但是我遇到了一个错误,我无法理解这个错误 这是我的简单代码: StreamReader reader = new StreamReader("hello.txt"); 但这给了我一个错误: 参数1:无法从“字符串”转换为“System.IO.Stream” 使用相同的代码,然后它就工作了,我做错了什么 如果要读取文件,最简单的方法是 var path = "c:\\mypath\\to\\my\\file.txt"; var line
StreamReader reader = new StreamReader("hello.txt");
但这给了我一个错误:
参数1:无法从“字符串”转换为“System.IO.Stream”
使用相同的代码,然后它就工作了,我做错了什么 如果要读取文件,最简单的方法是
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();
您是否尝试过清洁和重建?带有字符串参数的构造函数绝对有效。我假设这个错误在编译时是正确的?你使用什么框架?@d如果不知道所使用的框架,很难说,例如这个构造函数不包括在netStandardI中。我是c新手,在哪里可以看到我使用的框架?@d-j不同框架上的优点,在您的项目文件*.csproj中,您应该看到一个TargetFramework部分。如果您使用foreach,那么您应该使用file.ReadLines以避免将整个文件存储在内存中。计数器的用途是什么?另外,对于实现IDisposable的类型,您应该使用using模式或将文件放入finally块中。