DelimitedFileReader.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using JetBrains.Annotations;
  2. using NPOI.SS.Formula.Functions;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using TextFieldParserStandard;
  9. namespace InABox.Scripting
  10. {
  11. public class DelimitedFileReader : ITabularFileReader, IDisposable
  12. {
  13. private TextFieldParser _parser;
  14. public bool EndOfData => _parser.EndOfData;
  15. public Dictionary<string, int> Columns { get; set; }
  16. public DelimitedFileReader(Stream stream, string delimiter)
  17. {
  18. _parser = new TextFieldParser(stream);
  19. _parser.TextFieldType = FieldType.Delimited;
  20. _parser.SetDelimiters(delimiter);
  21. Columns = new();
  22. }
  23. public bool ReadHeader()
  24. {
  25. if (_parser.EndOfData)
  26. {
  27. return false;
  28. }
  29. Columns = _parser.ReadFields().Select((field, i) => (field, i)).ToDictionary(x => x.field, x => x.i);
  30. return true;
  31. }
  32. public bool SkipLine()
  33. {
  34. if (_parser.EndOfData)
  35. {
  36. return false;
  37. }
  38. _parser.ReadLine();
  39. return true;
  40. }
  41. public Dictionary<string, object?> ReadLine()
  42. {
  43. var values = _parser.ReadFields();
  44. return Columns.ToDictionary(
  45. x => x.Key,
  46. x =>
  47. {
  48. object? result = values[x.Value];
  49. return result;
  50. });
  51. }
  52. public void Dispose()
  53. {
  54. _parser.Dispose();
  55. }
  56. public IList<string> ReadLineValues() => _parser.ReadFields();
  57. }
  58. }