SensorCSVReader.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using System.IO;
  6. using System.Globalization;
  7. namespace CSVReader
  8. {
  9. public class SensorCSVReader
  10. {
  11. private string completeFileName;
  12. private char separator = ';';
  13. public SensorCSVReader(string filename)
  14. {
  15. completeFileName = Path.Combine(".", "Assets", "CSVInput", filename);
  16. if (!File.Exists(completeFileName))
  17. {
  18. completeFileName = "Err";
  19. Debug.Log("Unable to find Sensor File " + filename);
  20. }
  21. }
  22. /// <summary>
  23. /// Reads the entire File that has been found when Constructing the class instance. No streams are left open after the use of this method.
  24. /// If instance construction was not successfull, only return null.
  25. /// </summary>
  26. /// <returns>
  27. /// Returns a field of SensorObjects including all entries of the file
  28. /// </returns>
  29. public SensorObject[] ReadFile()
  30. {
  31. if (completeFileName == "Err")
  32. {
  33. return null;
  34. }
  35. string[] lines;
  36. try
  37. {
  38. lines = File.ReadAllLines(completeFileName);
  39. }
  40. catch (Exception e)
  41. {
  42. Debug.Log("Unable to Read Lines from Sensor File, " + e.Message);
  43. return null;
  44. }
  45. SensorObject[] sensors = new SensorObject[lines.Length];
  46. for (int i = 0; i < lines.Length; i++)
  47. {
  48. string[] elems = lines[i].Split(separator);
  49. try
  50. {
  51. sensors[i] = new SensorObject(int.Parse(elems[0]), float.Parse(elems[1].Replace(',', '.'), CultureInfo.InvariantCulture),
  52. float.Parse(elems[2].Replace(',', '.'), CultureInfo.InvariantCulture),
  53. float.Parse(elems[3].Replace(',', '.'), CultureInfo.InvariantCulture),
  54. float.Parse(elems[4].Replace(',', '.'), CultureInfo.InvariantCulture),
  55. float.Parse(elems[5].Replace(',', '.'), CultureInfo.InvariantCulture),
  56. float.Parse(elems[6].Replace(',', '.'), CultureInfo.InvariantCulture));
  57. }
  58. catch (Exception e)
  59. {
  60. Debug.Log("Sensorfile Error \"" + e.Message + "\" at line " + i);
  61. sensors[i] = null;
  62. }
  63. }
  64. return sensors;
  65. }
  66. }
  67. }