用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框的显 ...
随机推荐
- saltstack实战4--综合练习3
Saltstack配置管理-业务引用haproxy 在业务模块里写它的配置 各个业务是不同的,这里有差异性,所以没写在配置模块里. 对minion02也执行安装haproxy [root@master ...
- C#使用HttpHelper万能框架,重启路由器
首先声明,不是所有路由器都可以通过下面的代码来让路由器执行重启. 下面的代码测试的路由器是(TP-LINK TD-W89841N增强型).要根据自己的路由器来写代码. using CsharpHttp ...
- 实用工具推荐(Live Writer)(2015年05月26日)
1.写博客的实用工具 推荐软件:Live Writer 使用步骤: 1.安装 Live Essential 2011,下载地址:http://explore.live.com/windows-live ...
- (转)使用CruiseControl+SVN+ANT实现持续集成之三
在上一节中我们介绍了环境搭建和配置介绍,并快速启动CC查看集成结果,在本节中我们将详细介绍CC构建操作及监视. 1. 启动CC服务器 通过执行其根目录下的cruisecontrol.bat文件来启动C ...
- DOM_节点层次_Document类型
一.Document类型 nodeType: 9; nodeName: "#document"; nodeValue: null; parentValue: null; owner ...
- sqlplus 可以登录 plsql 不能登录
最开始我以为是system用户被锁定了,但是解锁后仍然不可以登录.大神指导之后可以了,说是缺少监听器,解决过程如下: 1.将“tnsnames.ora”和“listener.ora”两个文件里的“lo ...
- 关于RadAsm中GetEnvironmentStrings的BUG。
今天在asm中不通过msvcrt.inc调用c库. 所以.第一时间就在vc的lib中拷贝了libc.lib问价.加入工程后. 声明.调用如下: 然后.链接报错. libc.lib(crt0.obj) ...
- MDM基于IOS设备管控功能的所有命令介绍
前面我们介绍了IOS上MDM几个简单的控制命令的发送和返回数据的解析处理,下面我们介绍一下MDM涉及到的命令的操作介绍: 一.Control Commands(控制类命令) 1.Device Lock ...
- 7.JAVA_SE复习(文件)
文件和流 1.什么是节点流和处理流 InputStream & OutputStream Reader & Writer 乃节点流, 前面加File之类的名词 的节点流 其余加动词的均 ...
- 6.JAVA_SE复习(集合)
集合 结构图: 总结: 1.集合中的元素都是对象(注意不是基本数据类型),基本数据类型要放入集合需要装箱. 2.set与list的主要区别在于set中不允许重复,而list(序列)中可以有重复对象. ...