public async Task <HandlerResult <PdfFileModel> > Handle(DeletePdfFileCommand request, CancellationToken cancellationToken) { IEnumerable <byte> fileCopy = null; string fileLocation = string.Empty; try { var fileName = request.FileName.Trim(); var fileModel = await _repository.DeleteAsync(fileName); if (fileModel is null) { return(CreateFailureResult($"File record with name '{fileName}' does not exist in the database")); } fileLocation = fileModel.Location; if (!File.Exists(fileLocation)) { await _repository.SaveAsync(); return(CreateFailureResult($"File '{fileName}' does not exist on the server.")); } fileCopy = File.ReadAllBytes(fileLocation); File.Delete(fileModel.Location); await _repository.SaveAsync(); return(CreateSuccessResult(fileModel)); } catch (Exception ex) { if ( ex is DbException && !string.IsNullOrEmpty(fileLocation) && !File.Exists(fileLocation) && fileCopy != null) { File.WriteAllBytes(fileLocation, fileCopy.ToArray()); } return(CreateFailureResult($"Failed to delete file '{request.FileName}'", ex)); } }
public async Task <IActionResult> Delete([FromQuery] DeletePdfFileCommand deleteCommand) { var result = await _mediator.Send(deleteCommand); return(result.ToActionResult()); }