使用VB.NET控制台应用程序的进度条

时间:2015-05-04 12:30:54

标签: vb.net progress-bar console-application

我已将解析实用程序编写为控制台应用程序,并使其工作非常顺利。该实用程序读取分隔文件,并根据用户值作为命令行参数将记录拆分为2个文件之一(良好记录或错误记录)。

希望执行进度条或状态指示器以显示解析时执行的工作或剩余的工作。我可以轻松地写一个<。>在循环内的屏幕上,但想给出%。

谢谢!

3 个答案:

答案 0 :(得分:1)

首先你要知道你会期待多少行。 在你的循环中计算" intLineCount / 100 * intCurrentLine"

int totalLines = 0 // "GetTotalLines"
int currentLine = 0;
foreach (line in Lines)
{
  /// YOUR OPERATION

  currentLine ++;
  int progress = totalLines / 100 * currentLine;

  ///print out the result with the suggested method...
  ///!Caution: if there are many updates consider to update the output only if the value has changed or just every n loop by using the MOD operator or any other useful approach ;)
}

使用SetCursor方法将结果打印在循环中的相同位置 MSDN Console.SetCursorPosition

VB.NET:

Dim totalLines as Integer = 0
Dim currentLine as integer = 0
For Each line as string in Lines
     ' Your operation

     currentLine += 1I
     Dim Progress as integer = (currentLine / totalLines) * 100

    ' print out the result with the suggested method...
    ' !Caution: if there are many updates consider to update the output only if the value has changed or just every n loop by using the MOD operator or any other useful approach 

Next

答案 1 :(得分:1)

以下是如何计算完成百分比并将其输出到进度计数器的示例:

Option Strict On
Option Explicit On

Imports System.IO

Module Module1
    Sub Main()
        Dim filePath As String = "C:\StackOverflow\tabSeperatedFile.txt"
        Dim FileContents As String()


        Console.WriteLine("Reading file contents")
        Using fleStream As StreamReader = New StreamReader(IO.File.Open(filePath, FileMode.Open, FileAccess.Read))
            FileContents = fleStream.ReadToEnd.Split(CChar(vbTab))
        End Using

        Console.WriteLine("Sorting Entries")
        Dim TotalWork As Decimal = CDec(FileContents.Count)
        Dim currentLine As Decimal = 0D

        For Each entry As String In FileContents
            'Do something with the file contents

            currentLine += 1D
            Dim progress = CDec((currentLine / TotalWork) * 100)

            Console.SetCursorPosition(0I, Console.CursorTop)
            Console.Write(progress.ToString("00.00") & " %")
        Next

        Console.WriteLine()
        Console.WriteLine("Finished.")
        Console.ReadLine()

    End Sub
End Module

答案 2 :(得分:0)

那么最简单的方法是经常更新progressBar变量, 例如:如果您的代码包含大约100行或者可能是100个功能 在每个函数或某些代码行之后用百分比更新progressbar变量:)