DhcpEntryManager.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. using Utils;
  7. namespace DhcpServer
  8. {
  9. internal static class DhcpEntryManager
  10. {
  11. private static readonly string EntriesDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DhcpEntries");
  12. private static readonly HashSet<char> InvalidFileNameChars = new HashSet<char>(Path.GetInvalidFileNameChars());
  13. private static string FilterUserClass(string input)
  14. {
  15. if (input == null) return null;
  16. var sb = new StringBuilder(input);
  17. sb.FilterChars(InvalidFileNameChars);
  18. sb.Insert(0, '-');
  19. return sb.ToString();
  20. }
  21. private static string GetEntryPath(string mac, string userClass = null)
  22. {
  23. return Path.Combine(EntriesDir, "MAC-" + mac + FilterUserClass(userClass) + ".json");
  24. }
  25. private static string GetDefaultEntryPath(string userClass = null)
  26. {
  27. return Path.Combine(EntriesDir, "Default" + FilterUserClass(userClass) + ".json");
  28. }
  29. public static bool CreateDefaultEntryIfNoExist()
  30. {
  31. var path = GetDefaultEntryPath();
  32. if (File.Exists(path)) return false;
  33. if (false == Directory.Exists(EntriesDir)) Directory.CreateDirectory(EntriesDir);
  34. File.WriteAllText(path, JsonConvert.SerializeObject(new DhcpEntry(), Formatting.Indented));
  35. return true;
  36. }
  37. public static DhcpEntry GetDefaultEntry(string userClass = null)
  38. {
  39. var path = GetDefaultEntryPath(userClass);
  40. if (File.Exists(path)) return JsonConvert.DeserializeObject<DhcpEntry>(File.ReadAllText(path));
  41. var createNew = new DhcpEntry();
  42. File.WriteAllText(path, JsonConvert.SerializeObject(new DhcpEntry(), Formatting.Indented));
  43. return createNew;
  44. }
  45. public static DhcpEntry GetClientEntry(string mac, string userClass = null)
  46. {
  47. var path = GetEntryPath(mac, userClass);
  48. if (File.Exists(path)) return JsonConvert.DeserializeObject<DhcpEntry>(File.ReadAllText(path));
  49. var createNew = new DhcpEntry();
  50. File.WriteAllText(path, JsonConvert.SerializeObject(new DhcpEntry(), Formatting.Indented));
  51. return createNew;
  52. }
  53. }
  54. }