SoFunction
Updated on 2025-03-06

How to read csv format files in C#

        /// <summary>
/// Check whether the number of rows is valid
        /// </summary>
        /// <param name="col"></param> 
        private void CheckRowValid(int row)
        {
            if (row <= 0)
            {
throw new Exception("The number of rows cannot be less than 0");
            }
            if (row > RowCount)
            {
throw new Exception("No data for the current row");
            }
        }
        /// <summary>
/// Check whether the maximum number of rows is valid
        /// </summary>
        /// <param name="col"></param> 
        private void CheckMaxRowValid(int maxRow)
        {
            if (maxRow <= 0 && maxRow != -1)
            {
throw new Exception("The number of rows cannot be equal to 0 or less than -1");
            }
            if (maxRow > RowCount)
            {
throw new Exception("No data for the current row");
            }
        }
        /// <summary>
/// Check whether the number of columns is valid
        /// </summary>
        /// <param name="col"></param> 
        private void CheckColValid(int col)
        {
            if (col <= 0)
            {
throw new Exception("The number of columns cannot be less than 0");
            }
            if (col > ColCount)
            {
throw new Exception("No data for the current column");
            }
        }
        /// <summary>
/// Check whether the maximum number of columns is valid
        /// </summary>
        /// <param name="col"></param> 
        private void CheckMaxColValid(int maxCol)
        {
            if (maxCol <= 0 && maxCol != -1)
            {
throw new Exception("The number of columns cannot be equal to 0 or less than -1");
            }
            if (maxCol > ColCount)
            {
throw new Exception("No data for the current column");
            }
        }
        /// <summary>
///Load CSV file
        /// </summary>
        private void LoadCsvFile()
        {
//Verify the validity of the data
            if ( == null)
            {
throw new Exception("Please specify the CSV file name to load");
            }
            else if (!())
            {
throw new Exception("The specified CSV file does not exist");
            }
            else
            {
            }
            if ( == null)
            {
                = ;
            }
            StreamReader sr = new StreamReader(, );
            string csvDataLine;
            csvDataLine = "";
            while (true)
            {
                string fileDataLine;
                fileDataLine = ();
                if (fileDataLine == null)
                {
                    break;
                }
                if (csvDataLine == "")
                {
                    csvDataLine = fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
                }
                else
                {
                    csvDataLine += "\\r\\n" + fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
                }
//If you include even quotation marks, it means that a carriage return character or a comma appears in the data of the line.
                if (!IfOddQuota(csvDataLine))
                {
                    AddNewDataLine(csvDataLine);
                    csvDataLine = "";
                }
            }
            ();
//Odd quotes appear in the data line
            if ( > 0)
            {
throw new Exception("The format of the CSV file is incorrect");
            }
        }
        /// <summary>
/// Get two consecutive quotes into single quotes
        /// </summary>
/// <param name="fileDataLine">File Data Line</param>
        /// <returns></returns>
        private string GetDeleteQuotaDataLine(string fileDataLine)
        {
            return ("\\"\\"", "\\"");
        }
        /// <summary>
/// Determine whether the string contains odd quotation marks
        /// </summary>
/// <param name="dataLine">DataLine</param>
/// When <returns> is an odd number, it will return to true; otherwise it will return to false</returns>
        private bool IfOddQuota(string dataLine)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = 0; i < ; i++)
            {
                if (dataLine[i] == '\\"')
                {
                    quotaCount++;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }
        /// <summary>
/// Determine whether it starts with odd quotation marks
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private bool IfOddStartQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = 0; i < ; i++)
            {
                if (dataCell[i] == '\\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }
        /// <summary>
/// Determine whether it ends in odd quotes
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private bool IfOddEndQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = - 1; i >= 0; i--)
            {
                if (dataCell[i] == '\\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }
        /// <summary>
/// Add new data line
        /// </summary>
/// <param name="newDataLine">New DataLine</param>
        private void AddNewDataLine(string newDataLine)
        {
            //("NewLine:" + newDataLine);
            ////return;
            ArrayList colAL = new ArrayList();
            string[] dataArray = (',');
bool oddStartQuota;           // Whether to start with odd quotes
            string cellData;
            oddStartQuota = false;
            cellData = "";
            for (int i = 0; i < ; i++)
            {
                if (oddStartQuota)
                {
//Because the comma is divided before it, so you need to add a comma
                    cellData += "," + dataArray[i];
//Is it ending in odd quotes
                    if (IfOddEndQuota(dataArray[i]))
                    {
                        (GetHandleData(cellData));
                        oddStartQuota = false;
                        continue;
                    }
                }
                else
                {
//Does it start with odd quotes
                    if (IfOddStartQuota(dataArray[i]))
                    {
// Whether it ends with odd quotes, it cannot be a double quote, and it is not an odd quote
                        if (IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2 && !IfOddQuota(dataArray[i]))
                        {
                            (GetHandleData(dataArray[i]));
                            oddStartQuota = false;
                            continue;
                        }
                        else
                        {
                            oddStartQuota = true;
                            cellData = dataArray[i];
                            continue;
                        }
                    }
                    else
                    {
                        (GetHandleData(dataArray[i]));
                    }
                }
            }
            if (oddStartQuota)
            {
throw new Exception("There is a problem with the data format");
            }
            (colAL);
        }