Wednesday, June 19, 2019

c# Convert a non delimited txt file to a DataTable

This a a way to convert a non delimited txt file into a DataTable. First you would need another table with the definition of the file.  The table below would be the DataTable dt_Definition mentioned on the method below.

FieldType ReportColunmName Begin Length Order
Detail Last Name 1 30 1
Detail First Name 31 20 2
Detail Middle Initial 51 1 3
Detail Address 52 60 4
Detail City 112 30 5
Detail State 142 2 6
Detail Zip 144 10 7
Detail Phone AreaCode 154 3 8
Detail Phone 157 8 9
Detail Phone Ext 164 4 10
Detail Hope Phone 169 15 11
Detail Date of Birth 184 10 12
Detail Sex 194 1 13
Detail SSN 195 9 14

using System.IO;
using System.Data;

        static DataTable ConvertTxtFileToDataTable(string dataFile, DataTable dt_Definition)
        {
            DataTable retObj = new DataTable();
            try
            {
                //Add colunms
                foreach (DataRow row in dt_Definition.Rows)
                {
                    string reportColunmName = row["ReportColunmName"].ToString().Trim();
                    string recordType = row["FieldType"].ToString();
                    Int32 order = Int32.Parse(row["Order"].ToString());

                    if (order > 0 && recordType == "Detail")
                    {
                        retObj.Columns.Add(new DataColumn(reportColunmName, typeof(string)));
                    }
                }

                //Add rows
                bool isFirstLine = true;
                var lines = File.ReadAllLines(dataFile);
                foreach (string line in lines)
                {

                    string currentLine = line;

                    if (isFirstLine == false)
                    {
                        DataRow newRow = retObj.NewRow();
                        foreach (DataRow defRow in dt_Definition.Rows)
                        {

                            Int32 begin = Int32.Parse(defRow["Begin"].ToString()) - 1;
                            Int32 lenght = Int32.Parse(defRow["Length"].ToString());
                            string ReportColunmName = defRow["ReportColunmName"].ToString().Trim();

                            string value = currentLine.Substring(begin, lenght).Trim();
                            newRow[ReportColunmName] = value;
                        }
                        retObj.Rows.Add(newRow);
                    }
                    else
                    {
                        //Skip header row
                        isFirstLine = false;
                    }
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);

            }
            return retObj;

        }

No comments:

Post a Comment