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.

LocalStorageService.cs 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 LocalStorageService : StorageService
  13. {
  14. public LocalStorageService(StorageConfig config) : base(config)
  15. {
  16. }
  17. public override string GetUniqueFileName()
  18. {
  19. string filePath = FileHelper.GenerateRandomFileName(_config.LocalDirectory, _config.FileExtension, _config.FileNameLength);
  20. return Path.GetFileName(filePath);
  21. }
  22. public override List<string> GetFileNames()
  23. {
  24. return Directory.GetFiles(_config.LocalDirectory, "*.*", SearchOption.AllDirectories).Select(f => Path.GetFileName(f).ToLower()).ToList();
  25. }
  26. public override Stream GetFile(string fileName)
  27. {
  28. if (string.IsNullOrEmpty(fileName))
  29. return null;
  30. string filePath = GetFilePath(fileName);
  31. if (File.Exists(filePath))
  32. return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  33. return null;
  34. }
  35. public override void SaveEncryptedFile(string fileName, Stream file, int chunkSize, byte[] key, byte[] iv)
  36. {
  37. if (!Directory.Exists(_config.LocalDirectory))
  38. Directory.CreateDirectory(_config.LocalDirectory);
  39. string filePath = GetFilePath(fileName);
  40. AesCounterManaged.EncryptToFile(file, filePath, chunkSize, key, iv);
  41. }
  42. public override void SaveFile(string fileName, Stream file)
  43. {
  44. if (!Directory.Exists(_config.LocalDirectory))
  45. Directory.CreateDirectory(_config.LocalDirectory);
  46. string filePath = GetFilePath(fileName);
  47. // Just write the stream to the file
  48. using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
  49. {
  50. file.Seek(0, SeekOrigin.Begin);
  51. file.CopyTo(fileStream);
  52. }
  53. }
  54. public override void DeleteFile(string fileName)
  55. {
  56. string filePath = GetFilePath(fileName);
  57. // Delete the File
  58. if (File.Exists(filePath))
  59. {
  60. File.Delete(filePath);
  61. }
  62. }
  63. private string GetFilePath(string fileName)
  64. {
  65. if (string.IsNullOrEmpty(fileName))
  66. return null;
  67. string subDir = fileName[0].ToString().ToLower();
  68. return Path.Combine(_config.LocalDirectory, subDir, fileName);
  69. }
  70. }
  71. }