using System.Security.Cryptography; using StorageServer.Models; namespace StorageServer.IO; public class StorageProvider { public static int BufferSize = 16384; private string saveDirectory; public StorageProvider(string saveDirectory) { this.saveDirectory = saveDirectory; if (!Directory.Exists(saveDirectory)) { Directory.CreateDirectory(saveDirectory); } } public async Task ComputeStreamHash(Stream stream) { using (Stream buffered = new BufferedStream(stream, BufferSize)) { byte[] checksum = await SHA256.HashDataAsync(buffered); return BitConverter.ToString(checksum); } } public async Task SaveFile(FileModel fileModel, FileStream fs) { string saveFullName = GetFullPath(fileModel); using (FileStream dest = new FileStream(saveFullName, FileMode.OpenOrCreate)) { await fs.CopyToAsync(dest); } } public Stream GetFile(FileModel fileModel) { string saveFullName = GetFullPath(fileModel); if (!File.Exists(saveFullName)) { throw new FileNotFoundException(); } return new FileStream(saveFullName, FileMode.Open); } public void DeleteFile(FileModel fileModel) { string saveFullName = GetFullPath(fileModel); if (!File.Exists(saveFullName)) { throw new FileNotFoundException(); } File.Delete(saveFullName); } public string GetFullPath(FileModel fileModel) { string extension = Path.GetExtension(fileModel.FileName); string saveFileName = string.Format("{0}{1}", fileModel.FileID, extension); string saveFullName = Path.Combine(this.saveDirectory, saveFileName); return saveFullName; } }