我正在测试类 FileStream 和 StreamReader 如何协同工作。通过控制台应用程序。 我试图进入一个文件并读取行并将它们打印在控制台上。
我已经能够使用 while 循环来完成它,但我想使用 foreach 循环来尝试它。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace testing
{
public class Program
{
public static void Main(string[] args)
{
string file = @"C:\Temp\New Folder\New Text Document.txt";
using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
foreach(string line in file)
{
Console.WriteLine(line);
}
}
}
}
}
}
我一直收到的错误是:无法将类型“char”转换为“string”
确实有效的 while 循环看起来像这样:
while((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
我可能忽略了一些非常基本的东西,但我看不到它。
最佳答案
如果您想通过 foreach 逐行读取文件(以可重用的方式),请考虑以下迭代器 block :
public static IEnumerable<string> ReadLines(string path)
{
using (StreamReader reader = File.OpenText(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
请注意,这是延迟计算的 - 没有任何与 File.ReadAllLines()
关联的缓冲。 foreach
语法将确保迭代器被正确地 Dispose()
d,即使是异常,关闭文件:
foreach(string line in ReadLines(file))
{
Console.WriteLine(line);
}
(这个位只是为了兴趣而添加的......)
这种类型的抽象的另一个优点是它可以与 LINQ 完美搭配——即使用这种方法很容易进行转换/过滤等:
DateTime minDate = new DateTime(2000,1,1);
var query = from line in ReadLines(file)
let tokens = line.Split('\t')
let person = new
{
Forname = tokens[0],
Surname = tokens[1],
DoB = DateTime.Parse(tokens[2])
}
where person.DoB >= minDate
select person;
foreach (var person in query)
{
Console.WriteLine("{0}, {1}: born {2}",
person.Surname, person.Forname, person.DoB);
}
再一次,所有的计算都是惰性的(没有缓冲)。
关于c# - C#中的FileStream StreamReader问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/286533/