Source

main / Source / WebClient / Web.BizLogic / Helper / CsvHelper.cs

Full commit
Naethra D 3ee1b94 




















































using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace DataUp.Web.BizLogic
{
    /// <summary>
    /// Class containing methods used to Parse CSV files.
    /// </summary>
    public static class CsvHelper
    {
        private const string QUOTE = "\"";
        private const string ESCAPED_QUOTE = "\"\"";
        private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' };
        private static Regex csvSplitter = new Regex(@",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))");

        public static string[] ReadCsvValues(string input)
        {
            string[] values = csvSplitter.Split(input);

            for (int i = 0; i < values.Length; i++)
                values[i] = Escape(values[i]);

            return values;
        }

        public static string Escape(string value)
        {
            if (value.Contains(QUOTE))
                value = value.Replace(QUOTE, ESCAPED_QUOTE);

            if (value.IndexOfAny(CHARACTERS_THAT_MUST_BE_QUOTED) > -1)
                value = QUOTE + value + QUOTE;

            return value;
        }

        public static string Unescape(string value)
        {
            if (value.StartsWith(QUOTE) && value.EndsWith(QUOTE))
            {
                value = value.Substring(1, value.Length - 2);

                if (value.Contains(ESCAPED_QUOTE))
                    value = value.Replace(ESCAPED_QUOTE, QUOTE);
            }

            return value;
        }
    }
}