新規作成日 2017-07-10
最終更新日
テキストに加工を加えたい場合、テキストのファイルサイズが大きすぎる場合は、テキストファイルを1行ごとに読み込みます。
StreamReaderのPeek()メソッドは、次に読み込む文字の文字コードを返し、文字が無ければ-1を返します。 これを利用して、返された数値が0以上なら文字があるため読み込みを続け、0未満(-1)であったら終了すると言った分岐を行います。
using System;
using System.IO; //Streamを使うために必要です
// ファイルのテキストを一度に読み込む
class ReaderPractice
{
public static void Main()
{
StreamReader sReader = new StreamReader("test2.txt");
// エンコードのデフォルトはUTF-8
try
{
while (sReader.Peek() >= 0) //次に文字があればループを続ける
{
string result = sReader.ReadLine(); //1行読み込む
//文字列を処理します
// 文字色を白に変更する
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(result); //表示
// 1行づつ表示するための処理
Console.WriteLine("\n");
// 文字色を黄色に変更する
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("何かキーを押すと次の行を読み込みます。");
Console.WriteLine("\n");
Console.ReadKey();
}
sReader.Close(); //ストリームを閉じる
sReader.Dispose(); //ストリームをメモリから解放する
// コンソールが自動で閉じないための処理
Console.WriteLine("\n");
Console.WriteLine("何かキーを押すと終了します。");
Console.ReadKey();
}
catch (IOException e)
{
Console.WriteLine(e.Message); //エラーメッセージ出力
}
}
}

1行づつファイルを読み込む

読み込むテキストファイルは、「Debug」フォルダ内にコピーします。
