c# - C#中的FileStream StreamReader问题

标签 c#

我正在测试类 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/

相关文章:

c# - 如何获取ListView中被点击的item

c# - 如何序列化包含结构列表的类的对象列表

c# - Request.UrlReferrer 为空?

c# - 有效地用代码表达2x2逻辑网格

c# - 确保导出的 JPEG 小于最大文件大小

c# - 使用 MVC C# 和 MySql 的服务器端分页

c# - 已签名的应用程序如何使用未签名的程序集(可在客户站点重新生成)

c# - 为什么 Property 执行比 Field 或 Method 执行慢?

c# - Xtragrid 在删除过滤器时是否会触发任何事件?

c# - 代码契约(Contract),如果 X < Y 且 Y = Z+1 为什么 X < Z+1 未被证明