My requirement is I need to split a text file and store into a datatable. Refer
the following code and column separator “|” and row separator “^”:
var text = streamReader.ReadToEnd();
var lines = text.Split('^');
var rows = lines.Select(l => new {Line = l, Fields = l.Split('|')});
var colCount = rows.Max(r => r.Fields.Length);
var tblRegistration = new DataTable();
for (int i = 1; i <= colCount; i++)
{
tblRegistration.Columns.Add("Column" + i, typeof (string));
}
When it is correct format it will work fine.
But end user may upload text file like
adfafdsafsdfsdfs^fsdf|sfsdf|sdfsfd|dfs...
in the first row there is only one column, but there should be four.
In this case how to validate it?
If your desired result is that you fill every column from left to the right it’s easy:
So your example file would generate this
DataTable:If you want to throw an exception: