45 lines
1.5 KiB
C#
45 lines
1.5 KiB
C#
|
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) {
|
||
|
string extension = Path.GetExtension(fileModel.FileName);
|
||
|
string saveFileName = string.Format("{0}{1}", fileModel.FileID, extension);
|
||
|
string saveFullName = Path.Combine(this.saveDirectory, saveFileName);
|
||
|
using (FileStream dest = new FileStream(saveFullName, FileMode.OpenOrCreate)) {
|
||
|
await fs.CopyToAsync(dest);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public Stream GetFile(FileModel fileModel) {
|
||
|
string extension = Path.GetExtension(fileModel.FileName);
|
||
|
string saveFileName = string.Format("{0}{1}", fileModel.FileID, extension);
|
||
|
string saveFullName = Path.Combine(this.saveDirectory, saveFileName);
|
||
|
if (!File.Exists(saveFullName)) {
|
||
|
throw new FileNotFoundException();
|
||
|
}
|
||
|
|
||
|
return new FileStream(saveFullName, FileMode.Open);
|
||
|
}
|
||
|
}
|