You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

50 lines
1.3 KiB

  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Server;
  5. using Newtonsoft.Json;
  6. namespace MQTTnet.TestApp.UniversalWindows
  7. {
  8. public sealed class JsonServerStorage : IMqttServerStorage
  9. {
  10. readonly string _filename = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Retained.json");
  11. public Task SaveRetainedMessagesAsync(IList<MqttApplicationMessage> messages)
  12. {
  13. var json = JsonConvert.SerializeObject(messages);
  14. File.WriteAllText(_filename, json);
  15. return Task.CompletedTask;
  16. }
  17. public async Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
  18. {
  19. await Task.CompletedTask;
  20. if (!File.Exists(_filename))
  21. {
  22. return new List<MqttApplicationMessage>();
  23. }
  24. try
  25. {
  26. var json = File.ReadAllText(_filename);
  27. return JsonConvert.DeserializeObject<List<MqttApplicationMessage>>(json);
  28. }
  29. catch
  30. {
  31. return new List<MqttApplicationMessage>();
  32. }
  33. }
  34. public void Clear()
  35. {
  36. if (File.Exists(_filename))
  37. {
  38. File.Delete(_filename);
  39. }
  40. }
  41. }
  42. }