Skip to content

Commit bc93178

Browse files
committed
Tiny string optimization. Added stream unit test
1 parent 2786a40 commit bc93178

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

CsvExport/CsvExport.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ public string Export()
258258
ICsvWriter writer = new StringBuilderCsvWriter(sb);
259259

260260
if (_includeColumnSeparatorDefinitionPreamble)
261-
sb.Append("sep=" + _columnSeparator + "\r\n");
261+
sb.Append($"sep={_columnSeparator}\r\n");
262262

263263
foreach (var line in ExportToLines())
264264
{
@@ -309,7 +309,9 @@ public MemoryStream ExportAsMemoryStream(Encoding encoding = null)
309309
ICsvWriter writer = new StreamWriterCsvWriter(sw);
310310

311311
if (_includeColumnSeparatorDefinitionPreamble)
312-
sw.Write("sep=" + _columnSeparator + "\r\n");
312+
{
313+
sw.Write("sep="); sw.Write(_columnSeparator); sw.Write("\r\n"); //just tiny way to avoid string concatenation
314+
}
313315

314316
foreach (var line in ExportToLines())
315317
{

UnitTests/UnitTests.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,36 @@ public void TestEmptyGenericCollection()
232232
string csv = myExport.Export();
233233
Assert.AreEqual("sep=,", csv.Trim());
234234
}
235+
236+
[TestMethod]
237+
public void TestExportAsMemoryStream()
238+
{
239+
// Arrange
240+
var myExport = new CsvExport();
241+
myExport.AddRow();
242+
myExport["Region"] = "Los Angeles, USA";
243+
myExport["Sales"] = 100000;
244+
myExport["Date Opened"] = new DateTime(2003, 12, 31);
245+
246+
myExport.AddRow();
247+
myExport["Region"] = "Canberra \"in\" Australia";
248+
myExport["Sales"] = 50000;
249+
myExport["Date Opened"] = new DateTime(2005, 1, 1, 9, 30, 0);
250+
251+
// Act
252+
using var memoryStream = myExport.ExportAsMemoryStream();
253+
254+
// Assert
255+
Assert.IsNotNull(memoryStream);
256+
Assert.AreEqual(0, memoryStream.Position, "MemoryStream position should be reset to 0");
257+
258+
// Read the content and verify it matches expected CSV
259+
var content = Encoding.UTF8.GetString(memoryStream.ToArray());
260+
var contentWithoutBom = content.Trim(new char[] { '\uFEFF' }); // Remove BOM if present
261+
262+
var expectedCsv = "sep=,\r\nRegion,Sales,Date Opened\r\n\"Los Angeles, USA\",100000,2003-12-31\r\n\"Canberra \"\"in\"\" Australia\",50000,2005-01-01 09:30:00";
263+
Assert.AreEqual(expectedCsv, contentWithoutBom.Trim());
264+
}
235265
}
236266

237267
public class MyClass

0 commit comments

Comments
 (0)