流阅读器与多个文件

本文关键字:文件 | 更新日期: 2023-09-27 18:05:25

我似乎无法在整个网络中找到与此特定场景相关的任何问题/解决方案,因此我想我会对我试图使用StreamReader类型实现的内容进行分解。

基本上我有2个不平衡行计数的文件,即data1.txt包含包含20行,而data2.txt包含10行,所以我使用StreamReader首先从两个。txt文件读取数据,我想我可以使用while (((ts.transaction = t.r adline ()) !=null)||((ms.)master = t.r edline ()) !=null))从两个文件中读取总行,然后我可以继续应用额外的逻辑,将我的数据合并到第三个文件中。

然而,当我运行以下内容时,我遇到了"对象引用未设置为对象的实例",可能是因为行数不平衡?当我将while语句中的"||"替换为"&&"时,它似乎可以工作,但是我无法从两个文件中打印总行数。

现在我只是将文本附加到richTextBox1,以便测试我的数据输出。我想看看是否有更好的方法可以使用OR子句,或者我是否以正确的方式处理这个while条件?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    //Read Transaction File
    private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.Clear();
        StreamReader t = new StreamReader(@"c:'data1.txt");
        StreamReader m = new StreamReader(@"c:'data2.txt");
        transaction_storage ts = new transaction_storage();
        master_storage ms = new master_storage();
        while (((ts.transaction = t.ReadLine()) !=null)||((ms.master = t.ReadLine()) !=null))
        //while ((ts.transaction = t.ReadLine()) != null)
        {
            ms.m_index = Convert.ToInt32(ms.master.Substring(0, 2));
            ts.t_index = Convert.ToInt32(ts.transaction.Substring(0, 2));
            ts.t_name = ts.transaction.Substring(2, 10);
            ts.t_item = ts.transaction.Substring(10, 17);
            ts.t_amount = Convert.ToDouble(ts.transaction.Substring(ts.transaction.Length -7, 7));
            string transaction_data = (ts.t_index.ToString() + " " + ts.t_name + " " + ts.t_item + " " + ts.t_amount + "'n");
            string master_data = (ms.m_index.ToString());
            richTextBox1.AppendText(transaction_data);
            richTextBox1.AppendText(master_data);
        }
        t.Close();
        m.Close();
    }

    class master_storage
    {
        public int m_index;
        public string master;
    }
    class transaction_storage
    {
        public int t_index;
        public string t_name;
        public string t_item;
        public double t_amount;
        public string transaction;
    }
}

}

流阅读器与多个文件

先读取两个文件,然后使用简单的for循环执行逻辑:

var linesOfFile1 = File.ReadAllLines(@"c:'data1.txt");
var linesOfFile2 = File.ReadAllLines(@"c:'data2.txt");
for(int i = 0; i < Math.Min(linesOfFile1.Length, linesOfFile2.Length); i++) {
  //...
}