-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Escape the escape char when writing.
- Loading branch information
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
using CsvHelper.Configuration; | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Globalization; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Text.Json; | ||
using System.Text.Json.Nodes; | ||
using System.Threading.Tasks; | ||
using System.Xml.Linq; | ||
using Xunit; | ||
|
||
namespace CsvHelper.Tests.Writing | ||
{ | ||
public class WriteCustomEscapeTests | ||
{ | ||
[Fact] | ||
public void WriteField_CustomEscapeChar_ModeRFC4180_EscapesQuotesAndEscapeCharacter() | ||
{ | ||
var config = new CsvConfiguration(CultureInfo.InvariantCulture) | ||
{ | ||
HasHeaderRecord = false, | ||
Escape = '\\', | ||
}; | ||
using (var writer = new StringWriter()) | ||
using (var csv = new CsvWriter(writer, config)) | ||
{ | ||
// {"json":"{\"name\":\"foo\"}"} | ||
// json string -> csv field | ||
// "{\"json\":\"{\\\"name\\\":\\\"foo\\\"}\"}" | ||
csv.WriteField(@"{""json"":""{\""name\"":\""foo\""}""}"); | ||
csv.Flush(); | ||
|
||
var expected = @"""{\""json\"":\""{\\\""name\\\"":\\\""foo\\\""}\""}"""; | ||
Assert.Equal(expected, writer.ToString()); | ||
} | ||
} | ||
|
||
[Fact] | ||
public void WriteField_CustomEscapeChar_ModeEscape_EscapesQuotesAndEscapeCharacter() | ||
{ | ||
var config = new CsvConfiguration(CultureInfo.InvariantCulture) | ||
{ | ||
HasHeaderRecord = false, | ||
Escape = '\\', | ||
Mode = CsvMode.Escape, | ||
}; | ||
using (var writer = new StringWriter()) | ||
using (var csv = new CsvWriter(writer, config)) | ||
{ | ||
// {"json":"{\"name\":\"foo\"}"} | ||
// json string -> csv field | ||
// {\"json\":\"{\\\"name\\\":\\\"foo\\\"}\"} | ||
csv.WriteField(@"{""json"":""{\""name\"":\""foo\""}""}"); | ||
csv.Flush(); | ||
|
||
var expected = @"{\""json\"":\""{\\\""name\\\"":\\\""foo\\\""}\""}"; | ||
Assert.Equal(expected, writer.ToString()); | ||
} | ||
} | ||
} | ||
} |