From b7dc9f1c714874ac232e0efd541adc275870e338 Mon Sep 17 00:00:00 2001 From: Weihan Li Date: Wed, 18 Dec 2024 08:32:44 +0800 Subject: [PATCH] feat: add ToCsvFileAsync by TextWriter --- src/WeihanLi.Npoi/CsvHelper.cs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/WeihanLi.Npoi/CsvHelper.cs b/src/WeihanLi.Npoi/CsvHelper.cs index b62bafe..5d66626 100644 --- a/src/WeihanLi.Npoi/CsvHelper.cs +++ b/src/WeihanLi.Npoi/CsvHelper.cs @@ -610,6 +610,34 @@ public static bool ToCsvFile(this IEnumerable entities, string return true; } + public static async Task ToCsvFileAsync(this IEnumerable entities, string filePath, CsvOptions? csvOptions = null) + { + if (entities is null) + { + throw new ArgumentNullException(nameof(entities)); + } + + csvOptions ??= CsvOptions.Default; + + InternalHelper.EnsureFileIsNotReadOnly(filePath); + var dir = Path.GetDirectoryName(filePath); + if (dir.IsNotNullOrEmpty()) + { + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + } + + var lines = GetCsvLines(entities, csvOptions); + using var file = File.CreateText(filePath); + foreach (var line in lines) + { + await file.WriteLineAsync(line); + } + return true; + } + /// /// to csv bytes ///