Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CSVWriter
- {
- public CSVConfig CsvConfig { get; }
- public string Path { get; }
- public CSVWriter(string path, CSVConfig csvConfig)
- {
- Path = path;
- this.CsvConfig = csvConfig ?? CSVConfig.Default;
- }
- string ParseLine(IEnumerable<string> line)
- {
- string result = "";
- int count = 0;
- foreach (var cell in line)
- {
- result += ParseCell(cell);
- result += (count == (line.Count() - 1)) ? "\r\n" : ";";
- ++count;
- }
- return result;
- }
- // Передаешь коллекцию полей содержащихся в строке как оно есть.
- // Метод сам добавляет разделители и экранирует зарезервированные символы.
- public void Write(IEnumerable<string> line)
- {
- using (StreamWriter sw = new StreamWriter(Path))
- {
- sw.Write(ParseLine(line));
- }
- }
- string ParseCell(string cell)
- {
- cell.Replace(CsvConfig.NewLineMark, "");
- if (cell.Contains(CsvConfig.QuotationMark.ToString()) || cell.Contains(CsvConfig.Delimiter))
- {
- cell = cell.Replace(CsvConfig.QuotationMark.ToString(),
- string.Format("{0}{0}", CsvConfig.QuotationMark.ToString()));
- cell = string.Format("{1}{0}{1}", cell, CsvConfig.QuotationMark);
- }
- return cell;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement