使用streamReader类在c#中读取具有动态列数的文本文件 [英] using streamReader class to read text file with dynamic number of columns in c#

查看:41
本文介绍了使用streamReader类在c#中读取具有动态列数的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 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;

此代码面临的问题是,如果输入 LogFile 的列数超过 12 或更多,我会收到 索引超出范围异常.

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.

推荐答案

我有一个完全不同的方法,不使用任何列表.请原谅编码,这只是一个快速测试.

I have a totally different approach to this without using any Lists. Please excuse the coding, this is just a quick test.

首先,我将使用 DataTable.

First of all, I'm going to use a DataTable.

public DataTable dt = new DataTable();

我从每一行读入的数据将存储在一个 String 类型的数组中.

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());
                }
            }
        }

接下来,必须在哪里添加我们的 DataTable 行.我们行数据中的列数应始终与我们的 DataTable 中的列数相匹配,并且在最初执行此操作的位置每次都应该起作用:-

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();
    }

我在这个快速示例中所做的就是在表单 Load 中调用这些方法,然后为 DataGrid 添加数据源:-

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.

希望这会有所帮助.

*** 编辑 ****

*** EDIT ****

这是我使用的数据以及结果.

Here is the Data I used, along with Result.

这篇关于使用streamReader类在c#中读取具有动态列数的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆