0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】TextFieldParserで郵便番号データを処理する【ほぼパクリ】

Last updated at Posted at 2018-08-03

下記記事のコードの改変です。
LINQは本当に強力だ (6) TextFieldContext – kekyoの丼

単純にTextFieldParserクラスを使ったコンテキストをそのまま使うだけのサンプルが欲しかったので自分で改変してみました。
実行には、Microsoft.VisualBasicの参照設定が必要です。

参照設定.png

TextFieldクラスの部分はまるパクリで、呼び出すMainを簡略化しました。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.VisualBasic.FileIO;

namespace ContextTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // 郵便番号データのコンテキストを生成
            IEnumerable<string[]> context = TextField.Context(
                @"C:\うんたらかんたら\KEN_ALL.CSV", ",", Encoding.GetEncoding(932));

            // 結果をコンソールに出す
            foreach (string[] result in context.AsParallel())
            {
                foreach (string field in result) 
                {
                    Console.Write(field);
                    Console.Write(" ");
                }
                Console.WriteLine("");
            }

            Console.WriteLine("Enterで終了");
            Console.ReadLine();

        }
    }

    public static class TextField
    {
        // 指定されたCSVファイルへのコンテキストを生成する
        public static IEnumerable<string[]> Context(
            string path, string separator = ",", Encoding encoding = null)
        {
            using (Stream stream =
                new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (TextFieldParser parser =
                    new TextFieldParser(stream, encoding ?? Encoding.UTF8, true, false))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.Delimiters = new[] { separator };
                    parser.HasFieldsEnclosedInQuotes = true;
                    parser.TrimWhiteSpace = true;
                    while (parser.EndOfData == false)
                    {
                        string[] fields = parser.ReadFields();
                        yield return fields;
                    }
                }
            }
        }
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?