在C#中的FileStream的StreamReader问题 [英] FileStream StreamReader problem in C#
问题描述
我测试类的FileStream和StreamReader的是如何工作的togheter。通过一个控制台应用程序。
我试图去在一个文件中读取行并打印在控制台上。
I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application. I'm trying to go in a file and read the lines and print them on the console.
我已经能够用while循环做到这一点,但我想用foreach循环来试试吧。
I've been able to do it with a while-loop, but I want to try it with a foreach loop.
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);
}
}
}
}
}
}
我不断收到此错误是:无法将类型'字符'到'字符串'
The error I keep getting for this is: Cannot convert type 'char' to 'string'
while循环,它不工作,看起来是这样的:
The while loop, which does work, looks like this:
while((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
我可能真的俯瞰基本的东西,但我无法看到它。
I'm probably overlooking something really basic, but I can't see it.
推荐答案
要阅读新建文本文档.txt的所有行:
To read all lines in New Text Document.txt:
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))
{
while(!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
}
}
}
}
这篇关于在C#中的FileStream的StreamReader问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!