Example #1
0
        public async Task <FileSaveResponse> SaveToStorage(string subStorage, string fileName, object file, bool compress)
        {
            using (var uow = _dataService.StartUnitOfWork())
            {
                var fileResponse = new FileSaveResponse
                {
                    Filename = fileName
                };
                try
                {
                    var path = _fileStorage + subStorage + "\\";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var fileExtension = compress ? ".zip" : ".json";
                    var filePath      = path + fileName + fileExtension;
                    if (!File.Exists(filePath))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            if (compress)
                            {
                                using (var archive = new ZipFile())
                                {
                                    archive.AddEntry(fileName + ".json", file.ToJson());
                                    archive.Save(filePath);
                                }
                            }
                            else
                            {
                                await File.WriteAllTextAsync(filePath, file.ToJson());
                            }
                        }
                    }
                    var fileInfo = new FileInfo(filePath);
                    fileResponse.IsSuccess = true;
                    fileResponse.Hash      = fileInfo.CalculateMD5();
                    fileResponse.Path      = filePath;
                    fileResponse.Extension = fileExtension;
                }
                catch (Exception ex)
                {
                    fileResponse.IsSuccess    = false;
                    fileResponse.ErrorMessage = ex.Message;

                    _logger.LogError(ex, "Failed to save file {0}", fileName);
                }

                _logger.LogInformation("LocalFile: Finished saving {0} {1} success", fileName, fileResponse.IsSuccess ? "with" : "without");

                var result = uow.FileSaveResponseRepository.Add(fileResponse);
                uow.Commit();

                return(result);
            }
        }