/// <summary> /// Get the file path of file /// </summary> /// <param name="file"></param> /// <returns></returns> protected string GetFilePath(Dto.FileInfo file) { StringBuilder sb = new (); sb.Append(_appSettings.Configuration.FileDirectoryPath.TrimEnd(Path.DirectorySeparatorChar)); sb.Append(Path.DirectorySeparatorChar); sb.Append(file.Path.Replace("..", string.Empty)); sb.Append(Path.DirectorySeparatorChar); sb.Append(Path.GetFileName(file.Name)); return(sb.ToString()); }
/// <inheritdoc cref="IFileManager.DownloadFileByGuidAsync(Guid)" /> public async Task <byte[]> DownloadFileByGuidAsync(Guid fileId) { Dto.FileInfo file = (await _dbContext.KastraFiles .SingleOrDefaultAsync(f => f.FileId == fileId)) .ToFileInfo(); if (file is null) { throw new Exception($"{nameof(fileId)} not found"); } return(File.ReadAllBytes(GetFilePath(file))); }
/// <inheritdoc cref="IFileManager.AddFileAsync(Dto.FileInfo, Stream)"/> public async Task AddFileAsync(Dto.FileInfo file, Stream stream) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } if (file is null) { throw new ArgumentNullException(nameof(file)); } if (file.FileId != Guid.Empty && (await _dbContext.KastraFiles.AnyAsync(f => f.FileId == file.FileId))) { throw new ArgumentException($"{nameof(file.FileId)} already exists"); } // Generate new file id if (file.FileId == Guid.Empty) { file.FileId = Guid.NewGuid(); } // Get file path string filePath = GetFilePath(file); try { // Save file using (FileStream fileStream = System.IO.File.Create(filePath, (int)stream.Length)) { byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, bytesInStream.Length); fileStream.Write(bytesInStream, 0, bytesInStream.Length); } // Save file in database _dbContext.KastraFiles.Add(file.ToFile()); await _dbContext.SaveChangesAsync(); } catch (Exception) { File.Delete(filePath); throw; } }