Files
BeWoPlaner/Data/Access/LocalFileStorageDAO.cs
2025-06-05 14:03:55 +02:00

91 lines
2.5 KiB
C#

using BeWo.Data.Entities;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.Exceptions;
using BS.Shared.Interface;
using DevExpress.Mvvm.Native;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using Task = System.Threading.Tasks.Task;
namespace BeWo.Data.Access
{
public class LocalFileStorageDAO
{
private readonly string _rootPath;
public LocalFileStorageDAO(string rootPath)
{
_rootPath = rootPath;
}
private string GetFilePath(string filePath)
{
return Path.Combine(_rootPath, filePath);
}
public async Task SaveLogAsync(string pFileName, Stream content, CancellationToken cancellationToken = default)
{
var lFilePath = Path.Combine("logs", pFileName);
await SaveFileAsync(lFilePath, pFileName, content, cancellationToken).ConfigureAwait(true);
}
private async Task SaveFileAsync(string pFilePath, string pFileName, Stream content, CancellationToken cancellationToken = default)
{
// Prüfe Namen
if (SecurityUtils.ContainsInvalidFilenameChars(pFileName))
throw new BeWoInvalidOperationException(AppError.LocalFileStorageFileNameInvalidChar);
if (Path.GetFileName(pFilePath) != pFileName)
throw new BeWoInvalidOperationException(AppError.LocalFileStorageFileNameNotEqFilePath);
// Erstelle File Ordner
var path = GetFilePath(pFilePath);
var directory = Path.GetDirectoryName(path);
Directory.CreateDirectory(directory);
// Speichere Datei
using (var stream = File.Create(path))
{
await content.CopyToAsync(stream, bufferSize: 81920, cancellationToken).ConfigureAwait(true);
}
}
public Task<bool> FileExistsAsync(string pFilePath, CancellationToken cancellationToken = default)
{
return Task.FromResult(File.Exists(GetFilePath(pFilePath)));
}
public Task<Stream> GetFileAsync(string pFilePath, CancellationToken cancellationToken = default)
{
var path = GetFilePath(pFilePath);
if (!File.Exists(path))
return Task.FromResult<Stream>(null);
Stream stream = File.OpenRead(path);
return Task.FromResult(stream);
}
public Task<bool> DeleteFileAsync(string pFilePath, CancellationToken cancellationToken = default)
{
var path = GetFilePath(pFilePath);
if (File.Exists(path))
{
File.Delete(path);
return Task.FromResult(true);
}
return Task.FromResult(false);
}
}
}