[Up] C # CSV file read method

In many systems, you need to read csv file, I have encountered in a previous project by reading the data you want to csv file to datatable for processing, the following code

I used to write data to import csv file into the DataTable that it is now posted for everyone to share:

// GetCSVFile'S FileName and Data acquisition csv file data, and data into the DataTable

// mycsvdt csv file for containing data datatable, filepath csv file path means

private bool OpenCSVFile(ref DataTable mycsvdt,string filepath)
        {
            string strpath = filepath; //csv文件的路径
            try
            {
                int intColCount = 0;
                bool blnFlag = true;

                DataColumn mydc;
                DataRow mydr;
                
                string strline;
                string [] aryline;
                StreamReader mysr = new StreamReader(strpath,System.Text.Encoding.Default);

                while((strline = mysr.ReadLine()) != null)
                {
                    aryline = strline.Split(new char[]{','}); 

                    //给datatable加上列名
                    if (blnFlag)
                    {
                        blnFlag = false;
                        intColCount = aryline.Length;
                        int col=0;
                        for (int i = 0; i < aryline.Length; i++)
                        {
                            col=i+1;
                            mydc = new DataColumn(col.ToString());
                            mycsvdt.Columns.Add(mydc);
                        }
                    } 

                    // padding data and added to the datatable
                    mydr mycsvdt.NewRow = ();
                    for (int I = 0; I <intColCount; I ++)
                    {
                        mydr [I] = aryline [I];
                    }
                    mycsvdt.Rows.Add (mydr) ;
                }
                return to true;

            }
            the catch (Exception E)
            {
                
               
                the throw (Stack.GetErrorStack (strPath +. "CSV file data read error" + e.Message, "OpenCSVFile ("));
                return to false;
            }
        }

Reproduced in: https: //www.cnblogs.com/kevinGao/archive/2011/12/24/2336486.html

Guess you like

Origin blog.csdn.net/weixin_34179968/article/details/93053062