gpt4 book ai didi

c# - 控制台应用程序中的进度条

转载 作者:IT王子 更新时间:2023-10-29 03:42:57 27 4
gpt4 key购买 nike

我正在编写一个简单的 C# 控制台应用程序,用于将文件上传到 sftp 服务器。但是,文件量很大。我想显示已上传文件的百分比或仅显示已上传文件数占要上传文件总数的百分比。

首先,我得到了所有文件和文件总数。

string[] filePath = Directory.GetFiles(path, "*");
totalCount = filePath.Length;

然后我遍历文件并在 foreach 循环中将它们一个一个地上传。

foreach(string file in filePath)
{
string FileName = Path.GetFileName(file);
//copy the files
oSftp.Put(LocalDirectory + "/" + FileName, _ftpDirectory + "/" + FileName);
//Console.WriteLine("Uploading file..." + FileName);
drawTextProgressBar(0, totalCount);
}

在 foreach 循环中,我有一个进度条,但我遇到了问题。显示不正确。

private static void drawTextProgressBar(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.Gray;
Console.CursorLeft = position++;
Console.Write(" ");
}

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

//draw totals
Console.CursorLeft = 35;
Console.BackgroundColor = ConsoleColor.Black;
Console.Write(progress.ToString() + " of " + total.ToString() + " "); //blanks at the end remove any excess
}

输出只是 1943 年的 [ ] 0

我在这里做错了什么?

编辑:

我试图在加载和导出 XML 文件时显示进度条。但是,它正在经历一个循环。完成第一轮后,它会进入第二轮,依此类推。

string[] xmlFilePath = Directory.GetFiles(xmlFullpath, "*.xml");
Console.WriteLine("Loading XML files...");
foreach (string file in xmlFilePath)
{
for (int i = 0; i < xmlFilePath.Length; i++)
{
//ExportXml(file, styleSheet);
drawTextProgressBar(i, xmlCount);
count++;
}
}

它永远不会离开 for 循环...有什么建议吗?

最佳答案

我也在寻找控制台进度条。我没有找到一个可以满足我需要的,所以我决定自己动手。 Click here for the source code (麻省理工学院许可证)。

Animated progress bar

特点:

  • 使用重定向输出

    如果您重定向控制台应用程序的输出(例如 Program.exe > myfile.txt ),大多数实现都会因异常而崩溃。那是因为Console.CursorLeftConsole.SetCursorPosition()不支持重定向输出。

  • 实现 IProgress<double>

    这允许您将进度条与异步操作一起使用,报告 [0..1] 范围内的进度。

  • 线程安全

  • 快速

    Console class 因其糟糕的表现而臭名昭著。对它的调用太多,你的应用程序就会变慢。无论您报告进度更新的频率如何,此类每秒仅执行 8 次调用。

像这样使用它:

Console.Write("Performing some task... ");
using (var progress = new ProgressBar()) {
for (int i = 0; i <= 100; i++) {
progress.Report((double) i / 100);
Thread.Sleep(20);
}
}
Console.WriteLine("Done.");

关于c# - 控制台应用程序中的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com