テキストファイルを1行ごと読み込み
ファイル名:input.txt
あ 1
い 2
う 3
ファイル名:Program.cs
using System;
using System.IO;
namespace IteratorBlock01;
class Program
{
static void Main()
{
using StreamReader reader = new (@".\input.txt");
string? line;
while ((line = reader.ReadLine()) is not null)
{
string[] values = line.Split("\t");
foreach (string value in values)
{
Console.WriteLine(value);
}
}
}
}
結果
あ
1
い
2
う
3
テキストファイルを1行ごと読み込み(イテレーターブロック)
using System;
using System.IO;
namespace IteratorBlock01;
class Program
{
static public IEnumerable<string> ReadIterator(string filename)
{
using StreamReader reader = new (filename);
string? line;
while ((line = reader.ReadLine()) is not null)
{
yield return line;
}
}
static void Main()
{
const string filename = @".\input.txt";
foreach(string line in ReadIterator(filename))
{
string[] values = line.Split("\t");
foreach (string value in values)
{
Console.WriteLine(value);
}
}
}
}
コメント