2012年12月20日木曜日

C# でCSV形式のテキストファイルを読み込む

C# でCSV形式のテキストファイルを読み込むサンプル(テキストファイルはc:\mdb\zzz.txt)参照の追加でMicrosoft VisualBasic を追加しておく必要があります。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic.FileIO;
namespace cs_read_csv
{
class Program
{
static void Main(string[] args)
{
TextFieldParser parser = new TextFieldParser(@"C:\mdb\zzz.txt", Encoding.GetEncoding("Shift_JIS"));
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(","); // 区切り文字はコンマ
while (!parser.EndOfData)
{
string[] row = parser.ReadFields(); // 1行読み込み
Console.WriteLine(row[0] + "," + row[1] + "," + row[2]);
}
Console.ReadLine();
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿