From 531c094e7c5ffc89b851d00d5bc644f8dd8dab12 Mon Sep 17 00:00:00 2001 From: EthanHair Date: Thu, 6 Nov 2025 13:43:23 -0600 Subject: [PATCH] Create CSVDownloadService --- .../AstroPanda.Blazor.Toolkit.csproj | 3 ++- .../Services/CSVDownloadService.cs | 20 +++++++++++++++++++ .../Services/ICSVDownloadService.cs | 6 ++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 src/AstroPanda.Blazor.Toolkit/Services/CSVDownloadService.cs create mode 100644 src/AstroPanda.Blazor.Toolkit/Services/ICSVDownloadService.cs diff --git a/src/AstroPanda.Blazor.Toolkit/AstroPanda.Blazor.Toolkit.csproj b/src/AstroPanda.Blazor.Toolkit/AstroPanda.Blazor.Toolkit.csproj index bfc5b44..7f44907 100644 --- a/src/AstroPanda.Blazor.Toolkit/AstroPanda.Blazor.Toolkit.csproj +++ b/src/AstroPanda.Blazor.Toolkit/AstroPanda.Blazor.Toolkit.csproj @@ -8,7 +8,8 @@ - + + diff --git a/src/AstroPanda.Blazor.Toolkit/Services/CSVDownloadService.cs b/src/AstroPanda.Blazor.Toolkit/Services/CSVDownloadService.cs new file mode 100644 index 0000000..ec3d242 --- /dev/null +++ b/src/AstroPanda.Blazor.Toolkit/Services/CSVDownloadService.cs @@ -0,0 +1,20 @@ +using System.Text; + +namespace AstroPanda.Blazor.Toolkit.Services; + +public class CSVDownloadService(IDownloadService _downloads) : ICSVDownloadService +{ + public async Task DownloadLocalAsync(string fileName, IEnumerable collection) + { + using var stringWriter = new StringWriter(); + using var csvWriter = new CsvHelper.CsvWriter(stringWriter, System.Globalization.CultureInfo.InvariantCulture, true); + + csvWriter.WriteHeader(); + csvWriter.NextRecord(); + csvWriter.WriteRecords(collection); + + using var receivingStream = new MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString())); + + await _downloads.DownloadLocalAsync(fileName, receivingStream); + } +} diff --git a/src/AstroPanda.Blazor.Toolkit/Services/ICSVDownloadService.cs b/src/AstroPanda.Blazor.Toolkit/Services/ICSVDownloadService.cs new file mode 100644 index 0000000..2bd1ec0 --- /dev/null +++ b/src/AstroPanda.Blazor.Toolkit/Services/ICSVDownloadService.cs @@ -0,0 +1,6 @@ +namespace AstroPanda.Blazor.Toolkit.Services; + +public interface ICSVDownloadService +{ + public Task DownloadLocalAsync(string fileName, IEnumerable collection); +}