Implement a file content storage
Level: intermediate
Example
Create a class that implements the IFileContentStorage interface to create a content storage in the file system.
Implement a file content storage
namespace Terrasoft.Configuration {
using System.IO;
using System.Threading.Tasks;
using Terrasoft.File.Abstractions;
using Terrasoft.File.Abstractions.Content;
using Terrasoft.File.Abstractions.Metadata;
using Terrasoft.File.Metadata;
/// <summary>
/// Content storage in the file system.
/// </summary>
public class FsFileBlobStorage: IFileContentStorage {
// A root path to the storage.
private
const string BaseFsPath = "C:\\FsStore\\";
private static string GetPath(FileMetadata fileMetadata) {
var md = (EntityFileMetadata) fileMetadata;
string key = $ "{md.EntitySchemaName}\\{md.RecordId}_{fileMetadata.Name}";
return Path.Combine(BaseFsPath, key);
}
public Task <Stream> ReadAsync(IFileContentReadContext context) {
string filePath = GetPath(context.FileMetadata);
Stream stream = System.IO.File.OpenRead(filePath);
return Task.FromResult(stream);
}
public async Task WriteAsync(IFileContentWriteContext context) {
string filePath = GetPath(context.FileMetadata);
FileMode flags = context.WriteOptions != FileWriteOptions.SinglePart ?
FileMode.Append :
FileMode.OpenOrCreate;
string dirPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(dirPath)) {
Directory.CreateDirectory(dirPath);
}
using(var fileStream = System.IO.File.Open(filePath, flags)) {
context.Stream.CopyToAsync(fileStream);
}
}
public Task DeleteAsync(IFileContentDeleteContext context) {
string filePath = GetPath(context.FileMetadata);
System.IO.File.Delete(filePath);
return Task.CompletedTask;
}
public Task CopyAsync(IFileContentCopyMoveContext context) {
string sourceFilePath = GetPath(context.SourceMetadata);
string targetFilePath = GetPath(context.TargetMetadata);
System.IO.File.Copy(sourceFilePath, targetFilePath);
return Task.CompletedTask;
}
public Task MoveAsync(IFileContentCopyMoveContext context) {
string sourceFilePath = GetPath(context.SourceMetadata);
string targetFilePath = GetPath(context.TargetMetadata);
System.IO.File.Move(sourceFilePath, targetFilePath);
return Task.CompletedTask;
}
}
}