Posts Tagged CSV

Converting a DataTable to a CSV file

Posted by Ozer Senturk on Tuesday, 9 March, 2010
/// <summary>
/// Converts data table to csv file
/// </summary>
/// <param name="dt">The data table to convert</param>
/// <param name="fileName">The name of the csv file</param>
/// <param name="enclosure">The enclosure string to be used</param>
/// <param name="log">The log instance to be used</param>
public static void convertDataTableToCSVFile(
    DataTable dt,
    string fileName,
    string enclosure,
    Log log)
{
    log.log(String.Format("Creating CSV file to {0}", fileName));

    TextWriter textWriter =
        new StreamWriter(
            fileName);

    // Print headers to the file
    foreach (DataColumn dc in dt.Columns)
        textWriter.Write(enclosure + dc.Caption + enclosure + ";");

    textWriter.WriteLine();

    foreach (DataRow dr in dt.Rows)
    {
        foreach (DataColumn dc in dt.Columns)
            textWriter.Write(
                enclosure +
                dr[dc.Caption].ToString().Replace("\"", "\\\"").Replace(Environment.NewLine, "") +
                enclosure + ";");

        textWriter.WriteLine();
        textWriter.Flush();
    }

    textWriter.Close();

    log.log(String.Format("Created CSV file to {0}", fileName));
}

Wrapper on Microsoft’s TextFieldParser for reading CSV files

Posted by Ozer Senturk on Tuesday, 9 March, 2010
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualBasic.FileIO;

namespace CommonUtils
{
    #region CSVReader Class

    /// <summary>
    /// General purpose class for reading CSV Files
    /// </summary>
    public class CSVReader
    {
        /// <summary>
        /// The text field parser class to be used while parsing csv files
        /// </summary>
        private TextFieldParser textFieldParser;

        /// <summary>
        /// The delimiter member, default is ";"
        /// </summary>
        private String delimiter = ";";

        /// <summary>
        /// Getter and setter for delimiter member, default is ";"
        /// </summary>
        public String Delimiter
        {
            get
            {
                return delimiter;
            }
            set
            {
                delimiter = value;
                textFieldParser.SetDelimiters(delimiter);
            }
        }

        /// <summary>
        /// Enclosure flag, default is true
        /// </summary>
        private bool hasFieldsEnclosedInQuotes = true;

        /// <summary>
        /// Getter and setter for enclosure flag, default is true
        /// </summary>
        public bool HasFieldsEnclosedInQuotes
        {
            get
            {
                return hasFieldsEnclosedInQuotes;
            }
            set
            {
                hasFieldsEnclosedInQuotes = value;
                textFieldParser.HasFieldsEnclosedInQuotes = hasFieldsEnclosedInQuotes;
            }
        }

        /// <summary>
        /// Flag to determine whether the first line of the file holds field information or not, default is true
        /// </summary>
        public bool IsFirstLineHeader = true;

        /// <summary>
        /// Flag to indicate whether header line is indexed or not, default is false
        /// </summary>
        private bool hasReadFirstLineAsHeader;

        /// <summary>
        /// Dictionary to hold field information
        /// </summary>
        private Dictionary<string, int> dicFields = new Dictionary<string, int>();

        /// <summary>
        /// Getter for the keys of the dictionary to hold field information
        /// </summary>
        public Dictionary<string, int>.KeyCollection Fields
        {
            get
            {
                return dicFields.Keys;
            }
        }

        /// <summary>
        /// Current string array that holds field values of the current row
        /// </summary>
        private string[] currentFields;

        /// <summary>
        /// Property that holds the current line information
        /// </summary>
        private int currentLineNumber;

        /// <summary>
        /// Getter for current line number
        /// </summary>
        public int CurrentLineNumber
        {
            get
            {
                return currentLineNumber;
            }
        }

        /// <summary>
        /// Main constructor
        /// </summary>
        /// <param name="fileLocation">The location of the csv file to read</param>
        public CSVReader(String fileLocation)
        {
            textFieldParser = new TextFieldParser(fileLocation, Encoding.Default);
            textFieldParser.TextFieldType = FieldType.Delimited;
            textFieldParser.SetDelimiters(delimiter);
            textFieldParser.HasFieldsEnclosedInQuotes = hasFieldsEnclosedInQuotes;
        }

        /// <summary>
        /// Fetches the next line of the csv file
        /// </summary>
        /// <returns>True, if the fetch is successful, false, otherwise</returns>
        public bool Next()
        {
            if(IsFirstLineHeader &amp;&amp; !hasReadFirstLineAsHeader)
            {
                if (textFieldParser.EndOfData)
                    return false;

                String[] fieldNames = textFieldParser.ReadFields();
                currentLineNumber++;

                for (int i = 0; i < fieldNames.Length; i++)
                    dicFields.Add(fieldNames[i], i);

                hasReadFirstLineAsHeader = true;
            }

            if (textFieldParser.EndOfData)
                return false;

            currentFields = textFieldParser.ReadFields();
            currentLineNumber++;

            return true;
        }

        /// <summary>
        /// Overloads [] operator for this class
        /// </summary>
        /// <param name="fieldName">The name of the field</param>
        /// <returns>The value of the field</returns>
        public string this[string fieldName]
        {
            get
            {
                return this[dicFields[fieldName]];
            }
        }

        /// <summary>
        /// Overloads [] operator for this class
        /// </summary>
        /// <param name="fieldIndex">Index of the field</param>
        /// <returns>Value of the field</returns>
        public string this[int fieldIndex]
        {
            get
            {
                if (fieldIndex < currentFields.Length)
                    return currentFields[fieldIndex];

                return null;
            }
        }
    }

    #endregion
}