summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrakeWPF/Utilities/Output/CsvHelper.cs
blob: 0900308568d3e02f0f1646e4d6014153b04bd7d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CsvHelper.cs" company="HandBrake Project (http://handbrake.fr)">
//   This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
//   Utilitiy functions for writing CSV files
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HandBrakeWPF.Utilities.Output
{
    /// <summary>
    /// Utilitiy functions for writing CSV files
    /// </summary>
    internal sealed class CsvHelper
    {
        private const string QUOTE = "\"";
        private const string ESCAPED_QUOTE = "\"\"";
        private static readonly char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n', '\t' };

        /// <summary>
        /// Properly escapes a string value containing reserved characters with double quotes "..." before it is written to a CSV file.
        /// </summary>
        /// <param name="value">Value to be escaped</param>
        /// <returns>Fully escaped value</returns>
        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;
        }
    }
}