【问题标题】:"cannot convert from 'string' to 'System.IO.Stream'" while reading a file line by line using StreamReader使用 StreamReader 逐行读取文件时,“无法从 'string' 转换为 'System.IO.Stream'”
【发布时间】:2018-03-06 09:57:30
【问题描述】:

我正在按照在线教程在 c# 中逐行读取一个简单的文本文件,但我遇到了这个错误,我无法理解。

这是我的简单代码:

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

但这给了我一个错误:

论据 1:无法从 'string' 转换为 'System.IO.Stream'

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

【问题讨论】:

  • 您尝试过清洁和重建吗?带字符串参数的构造函数绝对有效。我假设这个错误在编译时是正确的?
  • 你使用什么框架?
  • @DanD 很难说不知道使用的框架,例如这个构造函数不包含在 netStandard 中也没有
  • 我是 c# 新手,在哪里可以看到我使用的框架?
  • @d-j 关于不同框架的好点,在您的项目文件 *.csproj 中,您应该看到 TargetFramework 部分。

标签: c# .net streamreader


【解决方案1】:

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

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

【讨论】:

  • 如果您使用的是foreach,那么您应该使用File.ReadLines() 以避免整个文件都在内存中。
【解决方案2】:

你可以这样做

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多