public async Task <Unit> Handle(SaveToCsv request, CancellationToken cancellationToken)
        {
            StreamWriter streamWriter = new StreamWriter(request.FilePath);
            CsvWriter    csvWriter    = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);
            await csvWriter.WriteRecordsAsync(request.Collection);

            await csvWriter.DisposeAsync();

            await _eventBus.Publish(new RecordsSavedToFile(request.FilePath, request.Collection.Count), cancellationToken);

            return(Unit.Value);
        }
示例#2
0
        public static async Task <byte[]> GetCsvByteArrayAsync <T>(this IEnumerable list)
            where T : ClassMap
        {
            MemoryStream ms     = null;
            StreamWriter writer = null;
            CsvWriter    csv    = null;

            try
            {
                var config = new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    SanitizeForInjection = true
                };

                ms     = new MemoryStream();
                writer = new StreamWriter(ms, Encoding.UTF8);
                csv    = new CsvWriter(writer, config);

                csv.Context.RegisterClassMap <T>();
                await csv.WriteRecordsAsync(list);

                await csv.FlushAsync();

                await writer.FlushAsync();

                await ms.FlushAsync();

                return(ms.ToArray());
            }
            finally
            {
                if (csv != null)
                {
                    await csv.DisposeAsync();
                }
                if (writer != null)
                {
                    await writer.DisposeAsync();
                }
                if (ms != null)
                {
                    await ms.DisposeAsync();
                }
            }
        }
示例#3
0
        public static async Task <string> CreateFile(int rows, string location = "", bool overwrite = false)
        {
            _userGenerator = new Faker <User>()
                             .RuleFor(u => u.Firstname, f => f.Name.FirstName())
                             .RuleFor(u => u.Lastname, f => f.Name.LastName())
                             .RuleFor(u => u.Avatar, f => f.Internet.Avatar())
                             .RuleFor(u => u.Username, (f, u) => f.Internet.UserName(u.Firstname, u.Lastname))
                             .RuleFor(u => u.Email, (f, u) => f.Internet.Email(u.Firstname, u.Lastname))
                             .RuleFor(u => u.SomethingUnique, f => $"Value {f.UniqueIndex}")
                             .RuleFor(u => u.SomeGuid, Guid.NewGuid);

            var filename = $"unsorted.{rows}.csv";
            var path     = string.IsNullOrWhiteSpace(location) ? Path.Combine(FileLocation, filename) : Path.Combine(location, filename);

            if (!overwrite)
            {
                if (File.Exists(path))
                {
                    Console.WriteLine($"File '{path}' already exists");
                    return(filename);
                }
            }

            Console.WriteLine($"Creating {path}...");
            await using var writer = new StreamWriter(path, append: false);
            await using var csv    = new CsvWriter(writer, CultureInfo.InvariantCulture);

            for (int i = 0; i < rows; i++)
            {
                csv.WriteRecord(_userGenerator.Generate());
                await csv.NextRecordAsync();
            }

            await csv.DisposeAsync();

            await writer.DisposeAsync();

            return(filename);
        }
示例#4
0
        public async ValueTask DisposeAsync()
        {
            await writer.DisposeAsync();

            await stream.DisposeAsync();
        }
        public async Task <OpenReddingLink> CreateBlobWithContents(IEnumerable <object>?results, CancellationToken cancellationToken)
        {
            ArgumentValidation.CheckNotNull(results, nameof(results));

            // Create a temp folder
            _logger.LogInformation("Creating temporary file resources...");
            string tempFolder   = $"{Directory.GetCurrentDirectory()}\\Temp";
            string fileName     = "salaries-" + Guid.NewGuid().ToString() + ".csv";
            string tempFilePath = Path.Combine(tempFolder, fileName);

            _logger.LogInformation($"File to create: {tempFilePath}");

            if (!Directory.Exists(tempFolder))
            {
                _logger.LogInformation($"{tempFolder} directory does not exist, creating...");
                Directory.CreateDirectory(tempFolder);
                _logger.LogInformation($"{tempFolder} directory created successfully!");
            }

            // Write text to the file
            _logger.LogInformation($"Writing file contents to {tempFilePath}");
            using var writer = new StreamWriter(tempFilePath);
            using var csv    = new CsvWriter(writer, CultureInfo.InvariantCulture);
            csv.WriteRecords(results);

            // Dispose of stream resources
            await writer.DisposeAsync();

            await csv.DisposeAsync();

            _logger.LogInformation($"CSV file created successfully, uploading blob to container: {_blobContainerClient.Name}");

            // Get a reference to a blob
            BlobClient blobClient = _blobContainerClient.GetBlobClient(fileName);

            // Open the file and upload its data
            _logger.LogInformation($"Updated file contents to blob location: {blobClient.Uri}");
            using FileStream uploadFileStream = File.OpenRead(tempFilePath);
            await blobClient.UploadAsync(uploadFileStream, true, cancellationToken : cancellationToken);

            uploadFileStream.Close();
            _logger.LogInformation("Blob successfully uploaded, cleaning up temporary resources...");

            // Clean up temporary resources
            File.Delete(tempFilePath);

            foreach (var file in Directory.GetFiles(tempFolder))
            {
                _logger.LogInformation($"Additional files detected in {tempFolder}, removing file {file}...");
                File.Delete(file);
                _logger.LogInformation($"{file} removed successfully!");
            }

            _logger.LogInformation($"Deleting temporary directory {tempFolder}...");
            Directory.Delete(tempFolder);
            _logger.LogInformation($"{tempFolder} successfully removed, returning blob URI: {blobClient.Uri.AbsoluteUri}");

            // Return the link to the blob
            return(new OpenReddingLink
            {
                Href = blobClient.Uri.AbsoluteUri,
                Method = nameof(HttpMethod.Get),
            });
        }