我想在C#中执行以下操作:
这是我到目前为止所拥有的:
private void Form1_Load(object sender, System.EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
int lineCount = 0;
int max = 100;
float percent;
using (var reader = File.OpenText(@"C:\file.txt"))
{
toolStripLabel1.Text = "Initializing...";
while (reader.ReadLine() != null)
{
lineCount++;
}
reader.Close();
for (int i = 0; i < lineCount; i++)
{
percent = (max / lineCount);
toolStripLabel1.Text = i.ToString() + " - " + percent + "%";
bw.ReportProgress(Convert.ToInt32(percent));
percent = percent + percent;
// Thread.Sleep(100);
}
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
// progressBar1.Value = (int)(((decimal)currentPosition / (decimal)length) * (decimal)100);
this.Text = e.ProgressPercentage.ToString();
}
任何人都知道如何根据从文件中读取的行来正确计算和显示进度条?
提前致谢!
答案 0 :(得分:4)
您的代码存在一些问题:
试试这个:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
var files = File.ReadAllLines( @"C:\file.txt" );
for( int i = 0; i < files.Length; i++ )
{
var line = files[i];
// do work on the current line here
int percentage = (int)( ( i / (double)files.Length ) * 100.0 );
bw.ReportProgress( percentage );
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
toolStripLabel1.Text = e.ProgressPercentage.ToString() + "%";
this.Text = e.ProgressPercentage.ToString();
}
如果文件非常大且需要花费时间的实际读数,您应该回到原来的阅读方式,但更新每行而不是之后的进度。虽然那时你又回到了在阅读文件之前不知道有多少行的问题。在这种情况下 - 您可以根据您读取的文件/字符数与文件的完整大小相比估算进度,无需全部阅读即可获得。
答案 1 :(得分:0)
您需要做一些事情 试试这个:替换
percent =(max / lineCount);
用这个
percent =(100.0 * i / lineCount);
并删除percent = percent + percent;
答案 2 :(得分:0)
试试这个:
private void InvokeLabel(string text)
{
if (toolStripLabel1.InvokeRequired)
{
toolStripLabel1.Invoke(new Action<string>(InvokeLabel), text);
}
else
{
toolStripLabel1.Text = text;
}
}
对于您的进度条,它是相同的代码