控制台进度百分比在一行中 [英] Console Progress Percent in one line

查看:47
本文介绍了控制台进度百分比在一行中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我试图显示当前的进度百分比看起来像这样



下载百分比:1%

下载百分比:2 %

下载百分比:3%

下载百分比:4%



这是错误的我希望它一个接一个地更新我的代码在下面可以有人请指出我哪里出错了。



Hi there im trying to display the progress percentage currently it looks like this

Downloaded Percentage: 1%
Downloaded Percentage: 2%
Downloaded Percentage: 3%
Downloaded Percentage: 4%

which is wrong i want it to update with out one after another my code is below can someone please point out where im going wrong.

var videoDownloader = new VideoDownloader(video,
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
                RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));

            for (int i = 0; i < videoDownloader.SavePath.Length; i++)
            {
                // Register the ProgressChanged event and print the current progress
                videoDownloader.DownloadProgressChanged += (sender, args) => Console.Write(string.Format("Downloaded Percentage: {0}", args.ProgressPercentage));
            }

推荐答案

您需要在开始之前保存光标位置,并且设置 [ ^ ]在您撰写邮件之前:

You need to save the cursor position before you start, and set it[^] before you write the message:
int left = Console.CursorLeft;
int top = Console.CursorTop;

videoDownloader.DownloadProgressChanged += (sender, args) => 
{
    Console.SetCursorPosition(left, top);
    Console.Write("Downloaded Percentage: {0}", args.ProgressPercentage);
};



(写入时,无需调用 string.Format 控制台; WriteLine 都有重载,接受复合格式字符串和参数。)


(There's no need to call string.Format when writing to the console; both Write and WriteLine have overloads which accept a composite format string and arguments.)


有一个技巧。



Console.Write(Something+\ rr )

会将光标返回到当前行的开头。



所以你会使用

Console.Write(Downloaded Percentage:{0,-3} \ r,args.ProgressPercentage);



由于线被覆盖,确保新文本至少与旧文本一样长是很重要的。因此在示例中使用了3个字符的左对齐字段。



另一种方法是用几个空格结束该行,例如

Console.Write(下载百分比:{0}%\ r,args.ProgressPercentage);

3个空格即可只要新行不超过原来的3个字符。



Alan。
There's a trick to this.

Console.Write("Something" + "\r")
will return the cursor back to the beginning of the current line.

So you would use
Console.Write("Downloaded Percentage: {0, -3}\r", args.ProgressPercentage);

As the line is overwritten it's important to ensure that the new text is at least as long as the old stuff. Hence the use of the 3 character left aligned field in the example.

An alternative is to just end the line with a few spaces, e.g.
Console.Write("Downloaded Percentage: {0}% \r", args.ProgressPercentage);
3 spaces will be ok as long as the new line is no more than 3 chars shorter than the original.

Alan.


这篇关于控制台进度百分比在一行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆