PageRenderTime 42ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/DataAccess/StreamingDataTable.cs

https://github.com/tpwalke2/DataTable
C# | 72 lines | 59 code | 9 blank | 4 comment | 6 complexity | 4b854183f10527525fa2d3bc7f7f5707 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Diagnostics;
  6. using System.Text.RegularExpressions;
  7. using System.Linq;
  8. namespace DataAccess
  9. {
  10. /// <summary>
  11. /// Stream rows from a file. This is ideal for large read-only files.
  12. /// </summary>
  13. internal class StreamingDataTable : DataTable
  14. {
  15. private readonly string _filename;
  16. private string[] _names;
  17. public StreamingDataTable(string filename)
  18. {
  19. _filename = filename;
  20. }
  21. public override IEnumerable<string> ColumnNames
  22. {
  23. get
  24. {
  25. if (_names == null)
  26. {
  27. using (TextReader sr = this.OpenText())
  28. {
  29. // First get columns.
  30. string header = sr.ReadLine();
  31. char ch = Reader.GuessSeparateFromHeaderRow(header);
  32. _names = Reader.split(header, ch);
  33. }
  34. }
  35. return _names;
  36. }
  37. }
  38. private TextReader OpenText()
  39. {
  40. return new StreamReader(_filename);
  41. }
  42. public override IEnumerable<Row> Rows
  43. {
  44. get
  45. {
  46. int columnCount = this.ColumnNames.Count();
  47. TextReader sr = this.OpenText();
  48. string header = sr.ReadLine(); // skip past header
  49. char chSeparator = Reader.GuessSeparateFromHeaderRow(header);
  50. string line;
  51. while ((line = sr.ReadLine()) != null)
  52. {
  53. string[] parts = Reader.split(line, chSeparator);
  54. if (parts.Length != columnCount)
  55. {
  56. continue; // skip malformed input
  57. }
  58. yield return new RowFromStreamingTable(parts, this);
  59. }
  60. }
  61. }
  62. }
  63. }