(1) C#でファイルを読み込み処理を行うサンプルプログラム
(1-1) 構文
(1-2) サンプルプログラム
(1-3) サンプルプログラムの補足
(1) C#でファイルを読み込み処理を行うサンプルプログラム
(1-1) 構文
どこまでを構文とするかは議論の余地ありますが、一旦今回は以下を構文としてご紹介します。
(構文)
using (StreamReader sr = new StreamReader([読み込みファイルパス], [エンコーディング方式]))
{
while (sr.EndOfStream == false)
{
string line = sr.ReadLine();
}
}
(1-2) サンプルプログラム
(サンプルプログラム)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReadFileSample
{
class Program
{
static void Main(string[] args)
{
//###(1)読み込むファイルのパスを指定
//### (例) string filepath = "C:\\Temp2\\IT0196\\Sample.log";
string filepath = "[ご自身の読み込むファイルパス]";
//###(2)tryの中にファイル読み込み処理を記述し、IOExceptionが発生したらcatch
try
{
//###(3)StreamReaderクラスを使ってファイルを読み込み
//### (usingステートメントを使うことでオブジェクトが有効な範囲の境界を指定)
using (StreamReader sr = new StreamReader(filepath, Encoding.UTF8))
{
//###(4)ファイルの終わりに達するまでの間、while内の処理を繰り返し
while (sr.EndOfStream == false)
{
//###(5)行の読み込み&コンソール表示
string line = sr.ReadLine();
Console.WriteLine(line);
}
}
}
//###(6)例外処理
catch (IOException e)
{
Console.WriteLine("Exception has occured");
//例外の内容をコンソール出力
Console.WriteLine(e.Message);
}
}
}
}
(図121⇒実行結果:正常パターン)

(図122⇒実行結果:例外パターン)

(1-3) サンプルプログラムの補足
(補足)
今回のプログラムは「コンソールアプリ (.NET Framework)」を使って作成しました。
(図132)