The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
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.

MemoryStorageService.cs 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Teknik.Configuration;
  8. using Teknik.Utilities;
  9. using Teknik.Utilities.Cryptography;
  10. namespace StorageService
  11. {
  12. public class MemoryStorageService : StorageService
  13. {
  14. private static Dictionary<string, byte[]> _files;
  15. private Dictionary<string, byte[]> Files
  16. {
  17. get
  18. {
  19. if (_files == null)
  20. _files = new Dictionary<string, byte[]>();
  21. return _files;
  22. }
  23. set
  24. {
  25. _files = value;
  26. }
  27. }
  28. public MemoryStorageService(StorageConfig config) : base(config)
  29. {
  30. }
  31. public override string GetUniqueFileName()
  32. {
  33. string filename = StringHelper.RandomString(_config.FileNameLength);
  34. while (Files.ContainsKey(string.Format("{0}.{1}", filename, _config.FileExtension)))
  35. {
  36. filename = StringHelper.RandomString(_config.FileNameLength);
  37. }
  38. return filename;
  39. }
  40. public override List<string> GetFileNames()
  41. {
  42. return Files.Keys.ToList();
  43. }
  44. public override Stream GetFile(string fileName)
  45. {
  46. if (string.IsNullOrEmpty(fileName))
  47. return null;
  48. if (!Files.ContainsKey(fileName))
  49. return null;
  50. return new MemoryStream(Files[fileName]);
  51. }
  52. public override void SaveEncryptedFile(string fileName, Stream file, int chunkSize, byte[] key, byte[] iv)
  53. {
  54. if (file == null ||
  55. Files.ContainsKey(fileName))
  56. return;
  57. using (var ms = new MemoryStream())
  58. {
  59. AesCounterManaged.EncryptToStream(file, ms, chunkSize, key, iv);
  60. Files.Add(fileName, ms.ToArray());
  61. }
  62. }
  63. public override void SaveFile(string fileName, Stream file)
  64. {
  65. if (file == null ||
  66. Files.ContainsKey(fileName))
  67. return;
  68. using (var ms = new MemoryStream())
  69. {
  70. file.Seek(0, SeekOrigin.Begin);
  71. file.CopyTo(ms);
  72. Files.Add(fileName, ms.ToArray());
  73. }
  74. }
  75. public override void DeleteFile(string fileName)
  76. {
  77. if (Files.ContainsKey(fileName))
  78. Files.Remove(fileName);
  79. }
  80. }
  81. }