選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JsonServerStorage.cs 1.4 KiB

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