Search code examples
c#filetextmergedatatable

How to merge many lines in text file and combine one row in datatable C#?


I have a text file that contains something like the following, content blocks separated by white lines empty

Apple
System IOS
Version 12

Samsung
Android
Version 10,11
US, Canada

Nokia
KaiOS system
Unknow

and I would like to merge many lines to new one line in DataTable, keep original format , the content of DataTable will be that, just have 3 rows

enter image description here

Any advice for this, please feel free share with me. Thank you all.


Solution

  • You just need to loop over the lines in the file and add a new row to the datatable each time you encounter an empty line.

    Something like this

    DataTable dt = new DataTable();
    var col = dt.Columns.Add("Description", typeof(string));
    StringBuilder linesBuffer = new StringBuilder();
    
    // Read one line using the enumerable version for reading txt files
    foreach (string line in File.ReadLines(@"e:\temp\datatable.txt"))
    {
        // Check if we have reached an empty line 
        // If so then add it to databable and reset the buffer
        if (string.IsNullOrWhiteSpace(line) && linesBuffer.Length != 0)
        {
            dt.Rows.Add(lineBuffer.ToString());
            linesBuffer.Length = 0;
        }
        else
            // add to the buffer reinserting the newline
            linesBuffer.AppendLine(line);
    }
    
    // do not forget to add the last lines block
    if(linesBuffer.Length > 0)
        dt.Rows.Add(linesBuffer.ToString());