2017-09-25 104 views
2

我在线阅读一个教程,在c#中逐行阅读一个简单的文本文件,但是我得到了这个错误,我无法包裹头部。在c#中使用StreamReader逐行读取文件

这是我简单的代码:

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

但是这给了我一个错误:

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

This article on msdn使用相同的代码,有它的作品,我究竟做错了什么?

+1

有你尝试一个干净的和重建?带有字符串参数的构造函数绝对有效。我假设这个错误是在编译时正确的? –

+0

你使用什么框架? –

+0

@DanD很难说如果不知道使用的框架,这个构造函数例如不包含在netStandard <2.0,这也是在netCore <2.0 –

回答

3

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

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

如果你使用'foreach',那么你应该使用'File.ReadLines()'来避免整个文件在内存中。 –

0

你可以这样做

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

'counter'有什么用?另外,对于实现'IDisposable'的类型,您应该使用'using'模式(或将'file.Close()'放在'finally'块中):请参见https://docs.microsoft.com/zh-cn/ -us/DOTNET /标准/垃圾收集/使用对象。 – benichka