【问题标题】:Linking third party CSV reader to a progress bar将第三方 CSV 阅读器链接到进度条
【发布时间】:2013-05-27 06:15:37
【问题描述】:

我从 Sebastien Lorion 编写的 link 中找到了一个编写良好的 CSV 解析器/读取器。

我喜欢这个 CSV 解析器的地方是我可以轻松地将它绑定到 DataGrid,例如:

using (CachedCsvReader csv = new
   CachedCsvReader(new StreamReader(txtChosenFile.Text), true))
        {
            dataGridView1.DataSource = csv;
        }

这是我的项目中需要的,因为我希望我的用户在将其提交到数据库之前对其进行预览。

但是,由于加载文件需要一段时间,我需要使用进度条至少向我的用户提供反馈。不幸的是,获得CachedCsvReader 类只是一个班轮,这使我很难在读取 csv 文件时链接或更新进度条。

如果它只是一个简单的 CsvReader 类,那么更新我的进度条会很容易,例如:

using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
        {
            using (CsvReader csv = new
       CsvReader(sr, true))
            {
                double progress = (double) sr.BaseStream.Position /  (double) sr.BaseStream.Length;
                progressBar1.Value = (int)progress*100;
            }

        }

但是,由于我使用的是CachedCsvReader,并且只有一个(或两个)班轮来上传 csv 阅读器而没有关于流位置和长度的信息,所以我无法更新我的进度条。

那么,将进度条连接到 CachedCsvReader 的最佳方式是什么?

【问题讨论】:

    标签: c# csv progress-bar streamreader


    【解决方案1】:

    假设您正在从名为Open 的方法启动读取,以下应该可以工作。它使用计时器控件每 1 秒轮询一次读取位置。

    private StreamReader sr;
    public void Open()
    {
        Timer timer = new Timer();
        timer.Interval = 1000;
        timer.Tick += new EventHandler(timer_Tick);
        timer.Enabled = true;
          timer.Start();
        using (this.sr = new StreamReader(openFileDialog1.FileName))
        {
            using (CachedCsvReader csv = new CachedCsvReader(sr, true))
            {
                dataGridView1.DataSource = csv;
            }
        }
          timer.Stop();
        timer.Enabled = false;
        timer.Tick -= new EventHandler(timer_Tick);
    }
    
    void timer_Tick(object sender, EventArgs e)
    {
        if (null != this.sr)
        {
            double progress = (double)sr.BaseStream.Position / (double)sr.BaseStream.Length;
            progressBar1.Value = (int)progress * 100;
        }
    }
    

    【讨论】:

    • 感谢@loopedcode 的回复。我尝试了您的代码,但它甚至没有进入 timer_Tick 事件(我试图调试它)。我试图使间隔更小但无济于事。但老实说,你的想法很好。
    • 我可以看到一个错字,它缺少对 timer.Start() 的调用;
    • 更新代码,看看是否有效。如果它仍然没有进入计时器块,那么您的文件可能被读取得非常快。
    • 同样的结果。但是你给了我一些开始,我感谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多