C method for reading files in csv format

  • 2020-11-30 08:31:15
  • OfStack

This article is an example of how C# reads files in csv format. Share to everybody for everybody reference. Specific implementation methods are as follows:

1. CSV file rules

The beginning of 1 is not left blank to the action unit.
2 May or may not contain column names, and column names are in line 1 of the file.
3 1 row data is not cross-row, no blank row.
A half - Angle comma (that is,) is used as a delimiter, and an empty column indicates its existence.
If a half-corner comma (that is,) exists for the 5-column contents, the field value is enclosed in half-corner quotes (that is,',').
If there are half-angle quotes (that is, ") in the 6 columns, replace them with half-angle double quotes ("") and enclose the field value with half-angle quotes (that is, "").
7 when a file is read or written in quotes, commas operate on the inverse of each other.
The format of the code is unlimited, ASCII, Unicode or other.
Special characters are not supported

2. C# methods for reading csv files

// read CSV File class , Read the specified CSV File that can be exported DataTable
    public class CsvStreamReader
    {
        private ArrayList rowAL;         // Line list ,CSV Each file 1 Line is 1 A chain
        private string fileName;        // The file name
        private Encoding encoding;        // coding
        public CsvStreamReader()
        {
            this.rowAL = new ArrayList();
            this.fileName = "";
            this.encoding = Encoding.Default;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"> The file name , Include file path </param>
        public CsvStreamReader(string fileName)
        {
            this.rowAL = new ArrayList();
            this.fileName = fileName;
            this.encoding = Encoding.Default;
            LoadCsvFile();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"> The file name , Include file path </param>
        /// <param name="encoding"> File coding </param>
        public CsvStreamReader(string fileName, Encoding encoding)
        {
            this.rowAL = new ArrayList();
            this.fileName = fileName;
            this.encoding = encoding;
            LoadCsvFile();
        }
        /// <summary>
        /// The file name , Include file path
        /// </summary>
        public string FileName
        {
            set
            {
                this.fileName = value;
                LoadCsvFile();
            }
        }
        /// <summary>
        /// File coding
        /// </summary>
        public Encoding FileEncoding
        {
            set
            {
                this.encoding = value;
            }
        }
        /// <summary>
        /// Get number of rows
        /// </summary>
        public int RowCount
        {
            get
            {
                return this.rowAL.Count;
            }
        }
        /// <summary>
        /// Get the number of columns
        /// </summary>
        public int ColCount
        {
            get
            {
                int maxCol;
                maxCol = 0;
                for (int i = 0; i < this.rowAL.Count; i++)
                {
                    ArrayList colAL = (ArrayList)this.rowAL[i];
                    maxCol = (maxCol > colAL.Count) ? maxCol : colAL.Count;
                }
                return maxCol;
            }
        }         /// <summary>
        /// Gets data for a row or column
        /// row: line ,row = 1 On behalf of the first 1 line
        /// col: column ,col = 1 On behalf of the first 1 column  
        /// </summary>
        public string this[int row, int col]
        {
            get
            {
                // Validation of data
                CheckRowValid(row);
                CheckColValid(col);
                ArrayList colAL = (ArrayList)this.rowAL[row - 1];
                // If the requested column data is greater than the current row column , Returns a null value
                if (colAL.Count < col)
                {
                    return "";
                }
                return colAL[col - 1].ToString();
            }
        }         /// <summary>
        /// It's generated by the smallest row, the largest row, the smallest column, the largest column 1 a DataTable Type of data
        /// Line is equal to the 1 On behalf of the first 1 line
        /// The column is equal to the 1 On behalf of the first 1 column
        /// maxrow: -1 Represents the largest row
        /// maxcol: -1 Represents the largest column
        /// </summary>
        public DataTable this[int minRow, int maxRow, int minCol, int maxCol]
        {
            get
            {
                // Validation of data
                CheckRowValid(minRow);
                CheckMaxRowValid(maxRow);
                CheckColValid(minCol);
                CheckMaxColValid(maxCol);
                if (maxRow == -1)
                {
                    maxRow = RowCount;
                }
                if (maxCol == -1)
                {
                    maxCol = ColCount;
                }
                if (maxRow < minRow)
                {
                    throw new Exception(" The maximum number of rows cannot be less than the minimum number of rows ");
                }
                if (maxCol < minCol)
                {
                    throw new Exception(" The maximum number of columns cannot be less than the minimum number of columns ");
                }
                DataTable csvDT = new DataTable();
                int i;
                int col;
                int row;
                // Increase the column
                for (i = minCol; i <= maxCol; i++)
                {
                    csvDT.Columns.Add(i.ToString());
                }
                for (row = minRow; row <= maxRow; row++)
                {
                    DataRow csvDR = csvDT.NewRow();
                    i = 0;
                    for (col = minCol; col <= maxCol; col++)
                    {
                        csvDR[i] = this[row, col];
                        i++;
                    }
                    csvDT.Rows.Add(csvDR);
                }
                return csvDT;
            }
        }         /// <summary>
        /// Check that 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(" There is no data for the current row ");
            }
        }
        /// <summary>
        /// Check that 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(" There is no data for the current row ");
            }
        }
        /// <summary>
        /// Check that the column count 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(" There is no data for the current column ");
            }
        }
        /// <summary>
        /// Check to see if 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(" There is no data for the current column ");
            }
        }
        /// <summary>
        /// load CSV file
        /// </summary>
        private void LoadCsvFile()
        {
            // Verify the validity of the data
            if (this.fileName == null)
            {
                throw new Exception(" Please specify what to load CSV The file name ");
            }
            else if (!File.Exists(this.fileName))
            {
                throw new Exception(" The specified CSV File does not exist ");
            }
            else
            {
            }
            if (this.encoding == null)
            {
                this.encoding = Encoding.Default;
            }
            StreamReader sr = new StreamReader(this.fileName, this.encoding);
            string csvDataLine;
            csvDataLine = "";
            while (true)
            {
                string fileDataLine;
                fileDataLine = sr.ReadLine();
                if (fileDataLine == null)
                {
                    break;
                }
                if (csvDataLine == "")
                {
                    csvDataLine = fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
                }
                else
                {
                    csvDataLine += "\\r\\n" + fileDataLine;//GetDeleteQuotaDataLine(fileDataLine);
                }
                // If it contains an even number of quotation marks, it indicates that the row has a carriage return or contains a comma
                if (!IfOddQuota(csvDataLine))
                {
                    AddNewDataLine(csvDataLine);
                    csvDataLine = "";
                }
            }
            sr.Close();
            // An odd number of quotation marks appears on the data line
            if (csvDataLine.Length > 0)
            {
                throw new Exception("CSV There is an error in the file format ");
            }
        }
        /// <summary>
        /// Gets the row of data where two consecutive quotes become single quotes
        /// </summary>
        /// <param name="fileDataLine"> File data line </param>
        /// <returns></returns>
        private string GetDeleteQuotaDataLine(string fileDataLine)
        {
            return fileDataLine.Replace("\\"\\"", "\\"");
        }
        /// <summary>
        /// Determines whether a string contains an odd number of quotes
        /// </summary>
        /// <param name="dataLine"> The data line </param>
        /// <returns> Is odd, return is true; Otherwise the return is false </returns>
        private bool IfOddQuota(string dataLine)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = 0; i < dataLine.Length; i++)
            {
                if (dataLine[i] == '\\"')
                {
                    quotaCount++;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }
        /// <summary>
        /// Determines whether to start with an odd number of 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 < dataCell.Length; i++)
            {
                if (dataCell[i] == '\\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }
        /// <summary>
        /// Determine if an odd number of quotation marks end
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private bool IfOddEndQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = dataCell.Length - 1; i >= 0; i--)
            {
                if (dataCell[i] == '\\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }
        /// <summary>
        /// Add a new data row
        /// </summary>
        /// <param name="newDataLine"> New data row </param>
        private void AddNewDataLine(string newDataLine)
        {
            //System.Diagnostics.Debug.WriteLine("NewLine:" + newDataLine);
            ////return;
            ArrayList colAL = new ArrayList();
            string[] dataArray = newDataLine.Split(',');
            bool oddStartQuota;        // Whether to start with an odd number of quotes
            string cellData;
            oddStartQuota = false;
            cellData = "";
            for (int i = 0; i < dataArray.Length; i++)
            {
                if (oddStartQuota)
                {
                    // Because it's separated by a comma , So put a comma there
                    cellData += "," + dataArray[i];
                    // Whether to end with an odd number of quotation marks
                    if (IfOddEndQuota(dataArray[i]))
                    {
                        colAL.Add(GetHandleData(cellData));
                        oddStartQuota = false;
                        continue;
                    }
                }
                else
                {
                    // Whether to start with an odd number of quotes
                    if (IfOddStartQuota(dataArray[i]))
                    {
                        // Whether to end with an odd number of quotation marks , Can't be 1 A double quotation marks , And it's not an odd number of quotes
                        if (IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2 && !IfOddQuota(dataArray[i]))
                        {
                            colAL.Add(GetHandleData(dataArray[i]));
                            oddStartQuota = false;
                            continue;
                        }
                        else
                        {
                            oddStartQuota = true;
                            cellData = dataArray[i];
                            continue;
                        }
                    }
                    else
                    {
                        colAL.Add(GetHandleData(dataArray[i]));
                    }
                }
            }
            if (oddStartQuota)
            {
                throw new Exception(" The data format is wrong ");
            }
            this.rowAL.Add(colAL);
        }         /// <summary>
        /// Remove the first and last quotes from the grid, and turn the double quotes into single quotes
        /// </summary>
        /// <param name="fileCellData"></param>
        /// <returns></returns>
        private string GetHandleData(string fileCellData)
        {
            if (fileCellData == "")
            {
                return "";
            }
            if (IfOddStartQuota(fileCellData))
            {
                if (IfOddEndQuota(fileCellData))
                {
                    return fileCellData.Substring(1, fileCellData.Length - 2).Replace("\\"\\"", "\\""); // Remove the first and last quotation marks, and then change the double quotation marks to single quotation marks
                }
                else
                {
                    throw new Exception(" Data quotes do not match " + fileCellData);
                }
            }
            else
            {
                // Considering form such as ""    """"      """"""  
                if (fileCellData.Length > 2 && fileCellData[0] == '\\"')
                {
                    fileCellData = fileCellData.Substring(1, fileCellData.Length - 2).Replace("\\"\\"", "\\""); // Remove the first and last quotation marks, and then change the double quotation marks to single quotation marks
                }
            }
            return fileCellData;
        }
    }

Hopefully, this article has helped you with your C# programming.


Related articles: