I have a tab delimited file with some columns and rows for example: some rows might not have value for some columns. What we know is that the \"order\" doe
Try following approach
static void Main(string[] args)
{
DataTable datatable = new DataTable();
StreamReader streamreader = new StreamReader(@"C:\Temp\txt.txt");
char[] delimiter = new char[] { '\t' };
string[] columnheaders = streamreader.ReadLine().Split(delimiter);
foreach (string columnheader in columnheaders)
{
datatable.Columns.Add(columnheader); // I've added the column headers here.
}
while (streamreader.Peek() > 0)
{
DataRow datarow = datatable.NewRow();
datarow.ItemArray = streamreader.ReadLine().Split(delimiter);
datatable.Rows.Add(datarow);
}
foreach (DataRow row in datatable.Rows)
{
Console.WriteLine(""----Row No: " + datatable.Rows.IndexOf(row) + "----"");
foreach (DataColumn column in datatable.Columns)
{
//check what columns you need
if (column.ColumnName == "Column2" ||
column.ColumnName == "Column12" ||
column.ColumnName == "Column45")
{
Console.Write(column.ColumnName);
Console.Write(" ");
Console.WriteLine(row[column]);
}
}
}
Console.ReadLine();
}
Just read all lines of your file, then split on tab delimiter, to gain access to each column.
var fileArray = File.ReadAllLines(myLocation);
for(int i=0;i<fileArray.Length;i++)
{
var line=fileArray[i];
if (i == 0)
{
//handle column names
}
else
{
var columns = line.Split('\t');
string value = columns[3];
}
}
You can use File.ReadLines() method (if you are using .NET Framework Version 4.0 or above) without any performance penalty as it would not load whole file content into Memory.
Try This:
using System.IO;
class FileData
{
public string Column2{ get; set; }
public string Column12{ get; set; }
public string Column45{ get; set; }
}
List<FileData> filedata = new List<FileData>();
FileData temp = new FileData();
foreach(var line in File.ReadLines("filepath.txt").Skip(1))
{
var tempLine = line.Split('\t');
temp.Column2 = tempLine[1];
temp.Column12 = tempLine[11];
temp.Column45 = tempLine[44];
filedata.Add(temp);
}
var list = from row in System.IO.File.ReadLines("file.txt")
let arr = row.Split('\t')
select new Tuple<string, string, string>(arr[2], arr[12], arr[45]);
Don't roll your own. There are...subtleties that aren't immediately apparent. Among others:
Instead, use something like Sebastien Lorion's most excellent Fast CSV Reader from CodeProject.
Edited to note: Despite the name, this is a general-purpose reader for delimited text files. Configurable items include