问题
public class myRows
{
public decimal Col1 { get; set; }
public decimal Col2 { get; set; }
public decimal Col3 { get; set; }
public decimal Col4 { get; set; }
public decimal Col5 { get; set; }
public decimal Col6 { get; set; }
public string myDateTimeCol { get; set; }
public myRows(string str)
{
var fields = str.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Col1 = Convert.ToDecimal(fields[0]);
Col2 = Convert.ToDecimal(fields[1]);
Col3 = Convert.ToDecimal(fields[2]);
Col4 = Convert.ToDecimal(fields[3]);
Col5 = Convert.ToDecimal(fields[4]);
Col6 = Convert.ToDecimal(fields[5]);
myDateTimeCol = string.Format("{0} {1} {2} {3} {4}", fields[6], fields[7], fields[8], fields[9], fields[10]);
}
}
I then read my LogFile like
var rows = new List<myRows>();
var sr = new StreamReader(txtFileToImport.Text);
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
if (!String.IsNullOrEmpty(s.Trim()))
{
rows.Add(new myRows(s));
}
}
sr.Close();
dataGridView_preView.DataSource = rows;

The problem am facing with this code is that, if the input LogFile has more than 12 or more columns, i get an index out of range exception.
Is there away i can re-factor the code to make it process any LogFile with any number of columns. The Log-files to be processed have varying number of columns, the only guarantee i have is that the date column(s) will always be the last column(s) in all cases.
回答1:
I have a totally different approach to this without using any Lists. Please excuse the coding, this is just a quick test.
First of all, I'm going to use a DataTable.
public DataTable dt = new DataTable();
The Data I read in from each line will be stored in an array of Type String.
public string[] data;
First thing we need to do is establish how many columns are in our data file. Below I count the number of instances and then generate a new the number of columns required.
public void addcolumns()
{
using (StreamReader reader = new StreamReader(@"C:\DataColumnTest.txt"))
{
string s = reader.ReadLine();
string[] col = s.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (var a in col)
{
dt.Columns.Add(new DataColumn());
}
}
}
Next up, Where going to have to add the rows our DataTable. The number of columns in our row data should always match the number of columns in our DataTable and as where doing this initially it should work every time :-
Public void addRows()
{
var sr = new StreamReader(@"C:\DataColumnTest.txt");
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
if (!String.IsNullOrEmpty(s.Trim()))
{
data = null;
data = s.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
dt.Rows.Add(data);
}
}
sr.Close();
}
All ive done for this quick example is call these methods in form Load, and then add the datasource for the DataGrid :-
private void Form1_Load(object sender, EventArgs e)
{
addcolumns();
addRows();
dataGridView1.DataSource = dt;
}
I know there will be cleaner ways of doing this, but it does work, unlike the other examples I've seen posted.
Hope This Helps.
*** EDIT ****
Here is the Data I used, along with Result.


回答2:
Try this:
public class myRows
{
public List<decimal> Cols = new List<decimal>();
public string myDateTimeCol { get; set; }
public string myVariableCols {
get{
var sb = new StringBuilder();
for (var x = 0; x < Cols.length; x++){
sb.Append( Cols[x].ToString() );
if (x < Cols.length - 1) sb.Append(" ");
}
return sb.ToString();
}
}
public myRows(string str)
{
var fields = str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
int x;
for (x = 0; x < fields.length-5;x++){
decimal d;
if (Decimal.TryParse(fields[x], out d)){
Cols.Add(d);
}
}
myDateTimeCol = string.Format("{0} {1} {2} {3} {4}", fields[x++], fields[x++], fields[x++], fields[x++], fields[x++]);
}
}
This should work for any column sizes if greater than 4. In your datagrid, you will have only two data-bound column: "myVariableCols" and "myDateTimeCol".
来源:https://stackoverflow.com/questions/13741302/using-streamreader-class-to-read-text-file-with-dynamic-number-of-columns-in-c-s