Я пытаюсь войти в файл, прочитать строки и распечатать их на консоли.
Мне удалось сделайте это с помощью цикла 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);
}
}
}
}
}
}
Цикл while, который работает, выглядит так:
Код: Выделить всё
while((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
Подробнее здесь: https://stackoverflow.com/questions/286 ... in-c-sharp