2 * Karinto Library Project
\r
4 * This software is distributed under a zlib-style license.
\r
5 * See license.txt for more information.
\r
10 using System.Collections.Generic;
\r
12 using System.Text.RegularExpressions;
\r
17 public class CsvReader<TDataSet> where TDataSet : IDataSet, new()
\r
19 private string separator = ",";
\r
21 public string Separator
\r
23 get { return separator; }
\r
28 /// カンマ以外だったらCSVじゃないような...?
\r
30 /// <param name="separator">区切り文字(正規表現可)</param>
\r
31 public void SetSeparator(string separator)
\r
33 this.separator = separator;
\r
39 /// <param name="path">CSVファイルのパス</param>
\r
40 /// <param name="proto">行の雛型</param>
\r
41 /// <returns>指定した型のリスト</returns>
\r
42 public List<TDataSet> Read(string path)
\r
44 return Read(path, new TDataSet());
\r
48 /// 雛型を指定してCSVファイルを読み込む
\r
50 /// <param name="path">CSVファイルのパス</param>
\r
51 /// <param name="proto">行の雛型</param>
\r
52 /// <returns>指定した型のリスト</returns>
\r
53 public List<TDataSet> Read(string path, TDataSet proto)
\r
55 List<TDataSet> records = new List<TDataSet>();
\r
59 using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
\r
61 using (StreamReader reader = new StreamReader(fs))
\r
65 string rfloat = @"\s*([-+]?(?:[0-9]+(\.[0-9]*)?|(\.[0-9]+))([eE][-+]?[0-9]+)?)\s*";
\r
66 Regex rCsv = new Regex(rfloat + separator, RegexOptions.Compiled);
\r
68 while (reader.Peek() >= 0)
\r
70 line = reader.ReadLine() + separator;
\r
71 //Console.WriteLine("> " + line);
\r
72 MatchCollection mc = rCsv.Matches(line);
\r
74 // 現状ではNaNが含まれる行は受理しない
\r
75 if (!proto.Width.Includes(mc.Count)) continue;
\r
77 if (proto.KeyRange != null)
\r
79 double key = Double.Parse(mc[0].Groups[1].Value);
\r
80 if (!proto.KeyRange.Includes(key)) continue;
\r
83 TDataSet c = new TDataSet();
\r
84 foreach (Match m in mc)
\r
86 c.Push(Double.Parse(m.Groups[1].Value));
\r
95 Console.WriteLine("The file could not be read:");
\r
96 Console.WriteLine("> " + path);
\r
97 Console.WriteLine(e.Message);
\r