StorageServer/IO/StorageProvider.cs

57 lines
1.8 KiB
C#
Raw Normal View History

2024-03-24 10:29:56 +09:00
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<string> 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) {
2024-03-24 14:17:48 +09:00
string saveFullName = GetFullPath(fileModel);
2024-03-24 10:29:56 +09:00
using (FileStream dest = new FileStream(saveFullName, FileMode.OpenOrCreate)) {
await fs.CopyToAsync(dest);
}
}
public Stream GetFile(FileModel fileModel) {
2024-03-24 14:17:48 +09:00
string saveFullName = GetFullPath(fileModel);
2024-03-24 10:29:56 +09:00
if (!File.Exists(saveFullName)) {
throw new FileNotFoundException();
}
return new FileStream(saveFullName, FileMode.Open);
}
2024-03-24 14:17:48 +09:00
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;
}
2024-03-24 10:29:56 +09:00
}