Advertisement
HAR1F

Writer

Mar 16th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. public class CSVWriter
  2.     {
  3.         public CSVConfig CsvConfig { get; }
  4.         public string Path { get; }
  5.  
  6.         public CSVWriter(string path, CSVConfig csvConfig)
  7.         {
  8.             Path = path;
  9.             this.CsvConfig = csvConfig ?? CSVConfig.Default;
  10.         }
  11.  
  12.         string ParseLine(IEnumerable<string> line)
  13.         {
  14.             string result = "";
  15.             int count = 0;
  16.             foreach (var cell in line)
  17.             {
  18.                 result += ParseCell(cell);
  19.                 result += (count == (line.Count() - 1)) ? "\r\n" : ";";
  20.                 ++count;
  21.             }
  22.  
  23.             return result;
  24.         }
  25.  
  26.         // Передаешь коллекцию полей содержащихся в строке как оно есть.
  27.         // Метод сам добавляет разделители и экранирует зарезервированные символы.
  28.         public void Write(IEnumerable<string> line)
  29.         {
  30.             using (StreamWriter sw = new StreamWriter(Path))
  31.             {
  32.                 sw.Write(ParseLine(line));
  33.             }
  34.         }
  35.  
  36.         string ParseCell(string cell)
  37.         {
  38.             cell.Replace(CsvConfig.NewLineMark, "");
  39.             if (cell.Contains(CsvConfig.QuotationMark.ToString()) || cell.Contains(CsvConfig.Delimiter))
  40.             {
  41.                 cell = cell.Replace(CsvConfig.QuotationMark.ToString(),
  42.                     string.Format("{0}{0}", CsvConfig.QuotationMark.ToString()));
  43.  
  44.                 cell = string.Format("{1}{0}{1}", cell, CsvConfig.QuotationMark);
  45.             }
  46.             return cell;
  47.         }
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement