固定長テキストの処理方法(.NET2.0)

.NET2.0のBCLを覗いていたら、System.Text.Parsingなるものを発見。Parserが転がっているのかと期待しましたが、TextFieldParserがあるだけでした。このクラスは固定長及び可変長のテキストが扱えますが、可変長はString.Splitに比べて何が嬉しいのかよく分からないので、固定長を処理させてみました。

#region Using directives

using System;
using System.IO;
using System.Text.Parsing;

#endregion

class Program
{
    static string text =
        "Essential .NET                          Don Box,Chris Sells \\4800\n" +
        "The Psychology of Computer Programming  Gerald M. Weinberg  \\2300\n" +
        "Dynamics of Software Development        Jim McCarthy        \\2200\n";

    static void Main(string args)
    {
        TextFieldParser parser = new TextFieldParser(new StringReader(text));
        // 固定長で読み込む
        parser.TextFieldType = FieldType.FixedWidth;
        // 空白は削除
        parser.TrimWhiteSpace = true;
        // フィールド長を指定
        parser.FieldWidths = new int { 40, 20, 5 };
        string[] fields;
        while ( (fields = parser.ReadFields()) != null)
        {
            foreach (string s in fields)
                Console.Write(s + "|");
            Console.WriteLine();
        }
        Console.ReadLine();
    }
}
/* 結果
Essential .NET|Don Box,Chris Sells|\4800|
The Psychology of Computer Programming|Gerald M. Weinberg|\2300|
Dynamics of Software Development|Jim McCarthy|\2200|
 */

固定長テキストを弄ることはあまり無い気がしますが、レガシーなシステムを移行するときには役立つかも?
ちなみに、System.Text.Parsingが所属するアセンブリMicrosoft.VisualBasic・・・