C # to convert TXT document to table

Time:2021-4-17

C # implementation of TXT document conversion

code:

public DataTable TXTToDataTable(string fileName, string columnName)
        {
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
            //Record one line of records read at a time
            string strLine = "";

            //Record the contents of each field in each line
            string[] aryLine;
            //Number of marked columns           
            int columnCount = 0;
            //Indicates whether it is the first line read
            bool IsFirst = true;

            if (IsFirst == true)
            {
                //strLine = "ATTENDANCE_DATE,EMP,ATTENDANCE_DEPT,EMP_TYPE,SHITF,PLANT_CODE";
                strLine = columnName;
                aryLine = strLine.Split(',');
                IsFirst = false;
                columnCount = aryLine.Length;
                //Create column
                for (int i = 0; i < columnCount; i++)
                {
                    DataColumn dc = new DataColumn(aryLine[i].ToUpper());
                    dt.Columns.Add(dc);
                }
            }

            //Read the data in txt line by line
            while ((strLine = sr.ReadLine()) != null)
            {
                aryLine =  strLine.Split ('\ t'); // tab separator
                DataRow dr = dt.NewRow();
                for (int j = 0; j < columnCount; j++)
                {
                    dr[j] = aryLine[j].ToUpper();
                }
                dt.Rows.Add(dr);
            }

            sr.Close();
            fs.Close();
            return dt;
        }