I receive a tab-delimited text file that must be parsed. Once parsed, the parts must be assigned to specific columns.
Here is an example of the code I'm using to do this:
string path = "C:\\Users\\Robert\\Desktop\\Test.txt";
FileInfo fileInfo = new FileInfo(path);
using (StreamReader streamReader = fileInfo.OpenText())
{
string line = "";
while ((line = streamReader.ReadLine()) != null)
{
string[] columns = line.Split('\t');
Output0Buffer.AddRow();
Output0Buffer.Column0 = columns[0];
Output0Buffer.Column1 = columns[1];
Output0Buffer.Column2 = columns[2];
Output0Buffer.Column3 = columns[3];
Output0Buffer.Column4 = columns[4];
}
}
The problem with this is that some of the lines in the text file don't have 5 columns and this code fails when it tries to assign the Column4 the value of columns[4] (in actuality, my real file has 21 parts, so this is more prone to failure).
How can a re-write this to only assign values to the Column4 (5,6 - 21) if there is actual data? Also, can this be written into a for or foreach loop to make it a bit tidier, so I don't have to have a line for all 21 columns?
Any help is greatly appreciated!