2014-10-01 101 views
2

我在C#控制檯應用程序中顯示進度條。它正在做一些小錯誤。控制檯應用程序中的進度條問題

這裏的進度條代碼:

private static void ProgressBar(int progress, int total) 
    { 
     //draw empty progress bar 
     Console.CursorLeft = 0; 
     Console.Write("["); //start 
     Console.CursorLeft = 32; 
     Console.Write("]"); //end 
     Console.CursorLeft = 1; 
     float onechunk = 30.0f/total; 

     //draw filled part 
     int position = 1; 
     for (int i = 0; i < onechunk * progress; i++) 
     { 
      Console.BackgroundColor = ConsoleColor.Green; 
      Console.CursorLeft = position++; 
      Console.Write(" "); 
     } 

     //draw unfilled part 
     for (int i = position; i <= 31; i++) 
     { 
      Console.BackgroundColor = ConsoleColor.Black; 
      Console.CursorLeft = position++; 
      Console.Write(" "); 
     } 

     //draw totals 
     Console.CursorLeft = 35; 
     Console.BackgroundColor = ConsoleColor.Black; 
     Console.Write(progress.ToString() + " of " + total.ToString() + " "); 
    } 

如果處理共5個文件會顯示:

即使正確地處理了所有5文件。

例如,我將XML文件從目錄加載到字符串數組中。

string[] xmlFilePath = Directory.GetFiles(xmlFullpath, "*.xml"); 

然後,我有一個for loop和它裏面我把我的進度條功能。

for (int i = 0; i < xmlFilePath.Length; i++) 
{ 
    ProgressBar(i, xmlFilePath.Length); 
} 

這就是我的工作方式。我知道,因爲它從0開始打印0 1 2 3 4 out of 5。 但是我想從5中的第一個開始打印,第5箇中的第2個....第5箇中的5個。

所以我改變了我的for循環的位置是1

for (int i = 1; i< xmlFilePath.Length; i++) 
{ 
} 

開始在這種情況下,將只處理4個文件,所以我改變xmlFilePath.LengthxmlFilePath.Length +1,但我發現index out bound例外。

關於如何解決這個問題的任何建議?

回答

1

只要告訴一個騙你的進度條

for (int i = 0; i < xmlFilePath.Length; i++) 
{ 
    ProgressBar(i + 1, xmlFilePath.Length); 
} 

只是另一個小問題。
我認爲你需要改變停止綠色街區的繪製條件

int position = 1; 
for (int i = 0; i <= onechunk * progress; i++) 
{ 
    Console.BackgroundColor = ConsoleColor.Green; 

    Console.CursorLeft = position++; 
    Console.Write(" "); 
} 

否則最後一個字符位置仍然是黑色的。

+0

我爲什麼沒有想到這個?! :) 謝謝。有效。 – smr5 2014-10-01 18:26:31

4

數組索引是0基礎的,所以你必須從0開始你可以做的是開始於指數0,而將數據傳遞到你的進度條,當加1

for (int i = 0; i < xmlFilePath.Length; i++) 
{ 
    ProgressBar(i + 1, xmlFilePath.Length); 
}