用C#实现控制台进度条
在写一些简单的控制台测试程序时,经常希望能够在程序运行的过程中实现进度条的功能以便查看程序运行的速度或者进度。本文以C#为例,实现简单的控制台进度条,以供大家参考(本文底部附下载地址)。
1.实现效果如下

2.控制台进度条实现类
/***********************************************************************
* 文 件 名:ProgressBar.cs
* CopyRight(C) 2016-2020 中国XX工程技术有限公司
* 文件编号:201603230001
* 创 建 人:张华斌
* 创建日期:2016-03-23
* 修 改 人:
* 修改日期:
* 描 述:控制台进度条实现类
***********************************************************************/
using System; namespace ProgressBarSolution
{
/// <summary>
/// 进度条类型
/// </summary>
public enum ProgressBarType
{
/// <summary>
/// 字符
/// </summary>
Character,
/// <summary>
/// 彩色
/// </summary>
Multicolor
} public class ProgressBar
{ /// <summary>
/// 光标的列位置。将从 0 开始从左到右对列进行编号。
/// </summary>
public int Left { get; set; }
/// <summary>
/// 光标的行位置。从上到下,从 0 开始为行编号。
/// </summary>
public int Top { get; set; } /// <summary>
/// 进度条宽度。
/// </summary>
public int Width { get; set; }
/// <summary>
/// 进度条当前值。
/// </summary>
public int Value { get; set; }
/// <summary>
/// 进度条类型
/// </summary>
public ProgressBarType ProgressBarType { get; set; } private ConsoleColor colorBack;
private ConsoleColor colorFore; public ProgressBar():this(Console.CursorLeft, Console.CursorTop)
{ } public ProgressBar(int left, int top, int width = , ProgressBarType ProgressBarType = ProgressBarType.Multicolor)
{
this.Left = left;
this.Top = top;
this.Width = width;
this.ProgressBarType = ProgressBarType; // 清空显示区域;
Console.SetCursorPosition(Left, Top);
for (int i = left; ++i < Console.WindowWidth;) { Console.Write(" "); } if (this.ProgressBarType == ProgressBarType.Multicolor)
{
// 绘制进度条背景;
colorBack = Console.BackgroundColor;
Console.SetCursorPosition(Left, Top);
Console.BackgroundColor = ConsoleColor.DarkCyan;
for (int i = ; ++i <= width;) { Console.Write(" "); }
Console.BackgroundColor = colorBack;
}
else
{
// 绘制进度条背景;
Console.SetCursorPosition(left, top);
Console.Write("[");
Console.SetCursorPosition(left + width-, top);
Console.Write("]");
}
} public int Dispaly(int value)
{
return Dispaly(value, null);
} public int Dispaly(int value, string msg )
{
if (this.Value != value)
{
this.Value = value; if (this.ProgressBarType == ProgressBarType.Multicolor)
{
// 保存背景色与前景色;
colorBack = Console.BackgroundColor;
colorFore = Console.ForegroundColor;
// 绘制进度条进度
Console.BackgroundColor = ConsoleColor.Yellow;
Console.SetCursorPosition(this.Left, this.Top);
Console.Write(new string(' ', (int)Math.Round(this.Value / (100.0 / this.Width))));
Console.BackgroundColor = colorBack; // 更新进度百分比,原理同上.
Console.ForegroundColor = ConsoleColor.Green;
Console.SetCursorPosition(this.Left + this.Width + , this.Top);
if (string.IsNullOrWhiteSpace(msg)) { Console.Write("{0}%", this.Value); } else { Console.Write(msg); }
Console.ForegroundColor = colorFore;
}
else
{
// 绘制进度条进度
Console.SetCursorPosition(this.Left+, this.Top);
Console.Write(new string('*', (int)Math.Round(this.Value / (100.0 / (this.Width - )))));
// 显示百分比
Console.SetCursorPosition(this.Left + this.Width + , this.Top);
if (string.IsNullOrWhiteSpace(msg)) { Console.Write("{0}%", this.Value); } else { Console.Write(msg); }
}
}
return value;
}
}
}
3.GZip文件操作类
/***********************************************************************
* 文 件 名:GZipHelper.cs
* CopyRight(C) 2016-2020 中国XX工程技术有限公司
* 文件编号:201603230002
* 创 建 人:张华斌
* 创建日期:2016-03-23
* 修 改 人:
* 修改日期:
* 描 述:GZip文件操作类
***********************************************************************/
using System;
using System.IO;
using System.IO.Compression; namespace ProgressBarSolution
{
/// <summary>
/// GZip文件操作类;
/// </summary>
public class GZipHelper
{
/// <summary>
/// 压缩文件;
/// </summary>
/// <param name="inputFileName">输入文件</param>
/// <param name="dispalyProgress">进度条显示函数</param>
public static void Compress(string inputFileName, Func<int, int> dispalyProgress = null)
{
using (FileStream inputFileStream = File.Open(inputFileName, FileMode.Open))
{
using (FileStream outputFileStream = new FileStream(Path.Combine(Path.GetDirectoryName(inputFileName), string.Format("{0}.7z", Path.GetFileNameWithoutExtension(inputFileName))), FileMode.Create, FileAccess.Write))
{
using (GZipStream gzipStream = new GZipStream(outputFileStream, CompressionMode.Compress))
{
byte[] buffer = new byte[];
int count = ;
while ((count = inputFileStream.Read(buffer, , buffer.Length)) > )
{
gzipStream.Write(buffer, , count);
if (dispalyProgress != null) { dispalyProgress(Convert.ToInt32((inputFileStream.Position / (inputFileStream.Length * 1.0)) * )); }
}
}
}
}
} /// <summary>
/// 解压文件
/// </summary>
/// <param name="inputFileName">输入文件</param>
/// <param name="outFileName">输出文件</param>
/// <param name="dispalyProgress">进度条显示函数</param>
public static void Decompress(string inputFileName, string outFileName, Func<int, int> dispalyProgress = null)
{
using (FileStream inputFileStream = File.Open(inputFileName, FileMode.Open))
{
using (FileStream outputFileStream = new FileStream(outFileName, FileMode.Create, FileAccess.Write))
{
using (GZipStream decompressionStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
{
byte[] buffer = new byte[];
int count = ;
while ((count = decompressionStream.Read(buffer, , buffer.Length)) > )
{
outputFileStream.Write(buffer, , count);
if (dispalyProgress != null) { dispalyProgress(Convert.ToInt32((inputFileStream.Position / (inputFileStream.Length * 1.0)) * )); }
}
}
}
}
}
}
}
4.控制台进度条测试程序
/***********************************************************************
* 文 件 名:Program.cs
* CopyRight(C) 2016-2020 中国XX工程技术有限公司
* 文件编号:201603230003
* 创 建 人:张华斌
* 创建日期:2016-03-23
* 修 改 人:
* 修改日期:
* 描 述:控制台进度条测试
***********************************************************************/
using System; namespace ProgressBarSolution
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine();
Console.WriteLine("正在压缩文件...");
ProgressBar progressBar = new ProgressBar(Console.CursorLeft, Console.CursorTop, , ProgressBarType.Character);
GZipHelper.Compress(@"D:\Temp\book.pdf", ProgressBar.Dispaly);
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("正在解压文件...");
progressBar = new ProgressBar(Console.CursorLeft, Console.CursorTop, , ProgressBarType.Multicolor);
GZipHelper.Decompress(@"D:\Temp\book.7z", @"D:\Temp\book.pdf", ProgressBar.Dispaly);
Console.WriteLine(); }
catch (System.ArgumentOutOfRangeException ex)
{
Console.Beep();
Console.WriteLine("进度条宽度超出可显示区域!");
}
finally
{
Console.WriteLine();
Console.WriteLine("操作完成,按任意键退出!");
Console.ReadKey(true);
}
}
}
}
5.下载地址
http://pan.baidu.com/s/1pKvzFjt
代码质量不高,请大家多指教(QQ: 823506006)。
用C#实现控制台进度条的更多相关文章
- [c#]控制台进度条的示例
看到[vb.net]控制台进度条的示例 感觉很好玩,翻译成C#版. using System; using System.Collections.Generic; using System.Linq; ...
- Python 控制台进度条的实现
进行爬虫等耗时的任务时,有时会想在控制台输出进度条,以显示当前任务进度.这里总结了两种方法. 方法1:使用tqdm模块 示例代码: from time import sleep from tqdm i ...
- ruby 编写控制台进度条
ruby 中,$stdout.flush 让控制台当前行内容可以重写,以此我们可以做出进度条的效果. def set_progress(index, char = '*') print (char * ...
- Python中如何写控制台进度条的整理
本文实例讲述了Python显示进度条的方法,是Python程序设计中非常实用的技巧.分享给大家供大家参考.具体方法如下: 首先,进度条和一般的print区别在哪里呢? 答案就是print会输出一个\n ...
- C#控制台进度条(Programming Progress bar in C# Consle application)
以下代码从Stack Overflow,觉得以后会用到就收藏一下,我是辛勤的搬运工,咿呀咿呀哟- 1.showing percentage in .net console application(在. ...
- [vb.net]控制台进度条的示例
Private Sub ConsoleProcessBar() Dim isBreak As Boolean = False Dim colorBack As ConsoleColor = Conso ...
- c# 控制台console进度条
1 说明 笔者大多数的开发在 Linux 下,多处用到进度条的场景,但又无需用到图形化界面,所以就想着弄个 console 下的进度条显示. 2 步骤 清行显示 //清行处理操作 int curren ...
- 小技巧:with用法 pycharm控制台输出带颜色的文字 打印进度条的
with用法 with用法在python中是一个很独特的用法,因为别的语言的中没有这个用法.所以针对这个特点我们来做一次总结,什么样的情况下可以同with 我们学到的有文件的操作,和acquire ...
- Ajax上传文件进度条显示
要实现进度条的显示,就要知道两个参数,上传的大小和总文件的大小 html5提供了一个上传过程事件,在上传过程中不断触发,然后用已上传的大 小/总大小,计算上传的百分比,然后用这个百分比控制div框的显 ...
随机推荐
- 一次配置jdk环境变量的感悟
开发java也一年多了,昨日一次偶然的机会,想在dos命令下执行一个程序,发现在 命令行输入 javac Test.java的时候,竟然提示javac不是内部命令, 之后输入 java ,也提示不是内 ...
- Java Concurrency - 浅析 CountDownLatch 的用法
The Java concurrency API provides a class that allows one or more threads to wait until a set of ope ...
- MyBatis(3.2.3) - Configuring MyBatis using XML, Settings
The default MyBatis global settings, which can be overridden to better suit application-specific nee ...
- asp.net上传文件时出现 404 - 找不到文件或目录。
昨天客户网站反应上传较大文件时出现404-找不到文件或目录的错误.如图: 网站上给出的提示是上传文件不能超过50M,但是在38M和40M这样的文件都不能上传了,显然不对. 在网上查了很久,第一个是检查 ...
- 用Dalvik指令集写个java类
Dalvik指令集 .class public LCalculate;#定义类名 .super Ljava/lang/Object;#定义父类 .method public static main([ ...
- 谷歌(Chrome)安装Advanced REST Client插件
进入Extensions(工具——>扩展程序) 点击Get More extensions或新建标签页点击网上应用店 如果加载太慢,出现chrome网上应用店无法打开,显示暂时无法加载该应用的画 ...
- Linux文件系统结构
准备写个Linux基础知识总结, 第一个想到的就是整理一个常用系统文件夹结构的说明,园子里“Aric小屋”的结构图整理的不错,我就不重复整理了,故借用一下
- C# 线程--第四线程实例
概述 在前面几节中和大家分享了线程的一些基础使用方法,本章结合之前的分享来编写一些日常开发中应用实例,和编写多线程时一些注意点.如大家有好的实例也欢迎分享.. 应用实例 应用:定时任务程序 场景:系统 ...
- BT之下拉菜单
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" ...
- lex&yacc4
yacc: we cannt use the $$ value dirictly. we need get it irrotly;