C#で、ファイルから一行ずつ読み出し、文字列を検索し、抽出する方法はいくつかありますが、正規表現を使う方法が一般的です。
以下に、ファイルから一行ずつ読み出し、正規表現を使って文字列を検索し、抽出するプログラムを記載します。
D:\test.txt
に以下のようなファイルがある場合において、1行ずつ文字列を読み出します。読み出す処理は、最終行まで繰り返し実施します。
正規表現パターンrgx
が、読みだした文字列に存在するかどうか、Matchオブジェクトの Successプロパティの値を確認して判断します。
一致が見つかった場合、返された Match オブジェクトの Value プロパティから部分文字列が含まれています。
一致が検出されない場合、値は String.Emptyです。
test1
test2
test3
test4
test5
using System;
using System.Text.RegularExpressions;
namespace LogRead
{
class Program
{
static void Main(string[] args)
{
Regex rgx = new Regex(@"test3", RegexOptions.IgnoreCase);
using (System.IO.StreamReader file = new System.IO.StreamReader(@"D:\test.txt", System.Text.Encoding.ASCII))
{
string line = "";
while ((line = file.ReadLine()) != null)
{
if (rgx.Match(line).Success)
{
Console.WriteLine(line);
System.Diagnostics.Debug.WriteLine(line);
}
}
}
System.Console.ReadLine();
}
}
}
ただし、上記の場合では、例えば、ファイルが見つからない場合は、例外が発生してしまいます。
そのような場合は、try catch節を用いるとよいでしょう。
using System;
using System.Text.RegularExpressions;
namespace LogRead
{
class Program
{
static void Main(string[] args)
{
Regex rgx = new Regex(@"test3", RegexOptions.IgnoreCase);
try
{
using (System.IO.StreamReader file = new System.IO.StreamReader(@"D:\test.tst", System.Text.Encoding.ASCII))
{
string line = "";
while ((line = file.ReadLine()) != null)
{
if (rgx.Match(line).Success)
{
Console.WriteLine(line);
System.Diagnostics.Debug.WriteLine(line);
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
System.Console.ReadLine();
}
}
}
以下のように、エラー内容を取得することができました。
環境について
- IDE : Microsoft Visual Studio Community 2017
- プロジェクト : C# コンソールアプリケーション