PersistentWizardData.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using UnityEngine;
  7. namespace TheraBytes.BetterUi.Editor
  8. {
  9. public class PersistentWizardData
  10. {
  11. const char SEPARATOR = '=';
  12. string filePath;
  13. Dictionary<string, string> data;
  14. public int SavedDataCount { get { return (data != null) ? data.Count : 0; } }
  15. public PersistentWizardData(string filePath)
  16. {
  17. this.filePath = filePath;
  18. }
  19. public bool FileExists()
  20. {
  21. return File.Exists(filePath);
  22. }
  23. public bool TryDeserialize()
  24. {
  25. if (!FileExists())
  26. return false;
  27. try
  28. {
  29. this.data = new Dictionary<string, string>();
  30. string[] lines = File.ReadAllLines(filePath);
  31. foreach (string l in lines)
  32. {
  33. string[] kv = l.Split(new char[] { SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
  34. data.Add(kv[0], kv[1]);
  35. }
  36. return true;
  37. }
  38. catch (Exception ex)
  39. {
  40. data.Clear();
  41. Debug.LogError("could not deserialize wizard data: " + ex);
  42. return false;
  43. }
  44. }
  45. public bool TryGetValue(string key, out string parsableValueString)
  46. {
  47. if(data == null)
  48. {
  49. if(TryDeserialize() == false)
  50. {
  51. parsableValueString = null;
  52. return false;
  53. }
  54. }
  55. return data.TryGetValue(key, out parsableValueString);
  56. }
  57. public void RegisterValue(string key, string parsableValueString)
  58. {
  59. if (data == null)
  60. {
  61. if (!TryDeserialize())
  62. {
  63. data = new Dictionary<string, string>();
  64. }
  65. }
  66. data[key] = parsableValueString;
  67. }
  68. public bool RemoveEntry(string key)
  69. {
  70. if (data == null)
  71. {
  72. if (!TryDeserialize())
  73. {
  74. return false;
  75. }
  76. }
  77. return data.Remove(key);
  78. }
  79. public void Save()
  80. {
  81. // ensure the directory exists
  82. var dir = Path.GetDirectoryName(filePath);
  83. if(!Directory.Exists(dir))
  84. {
  85. Directory.CreateDirectory(dir);
  86. }
  87. // ensure that there is no old data at the end of the file after save.
  88. if(FileExists())
  89. {
  90. File.Delete(filePath);
  91. }
  92. // save the data
  93. using(FileStream stream = File.OpenWrite(filePath))
  94. {
  95. using(StreamWriter sw = new StreamWriter(stream))
  96. {
  97. foreach(var kv in data)
  98. {
  99. sw.WriteLine(string.Format("{0}{2}{1}", kv.Key, kv.Value, SEPARATOR));
  100. }
  101. }
  102. }
  103. }
  104. }
  105. }