在写一些简单的控制台测试程序时,经常希望能够在程序运行的过程中实现进度条的功能以便查看程序运行的速度或者进度。本文以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#实现控制台进度条的更多相关文章

  1. [c#]控制台进度条的示例

    看到[vb.net]控制台进度条的示例 感觉很好玩,翻译成C#版. using System; using System.Collections.Generic; using System.Linq; ...

  2. Python 控制台进度条的实现

    进行爬虫等耗时的任务时,有时会想在控制台输出进度条,以显示当前任务进度.这里总结了两种方法. 方法1:使用tqdm模块 示例代码: from time import sleep from tqdm i ...

  3. ruby 编写控制台进度条

    ruby 中,$stdout.flush 让控制台当前行内容可以重写,以此我们可以做出进度条的效果. def set_progress(index, char = '*') print (char * ...

  4. Python中如何写控制台进度条的整理

    本文实例讲述了Python显示进度条的方法,是Python程序设计中非常实用的技巧.分享给大家供大家参考.具体方法如下: 首先,进度条和一般的print区别在哪里呢? 答案就是print会输出一个\n ...

  5. C#控制台进度条(Programming Progress bar in C# Consle application)

    以下代码从Stack Overflow,觉得以后会用到就收藏一下,我是辛勤的搬运工,咿呀咿呀哟- 1.showing percentage in .net console application(在. ...

  6. [vb.net]控制台进度条的示例

    Private Sub ConsoleProcessBar() Dim isBreak As Boolean = False Dim colorBack As ConsoleColor = Conso ...

  7. c# 控制台console进度条

    1 说明 笔者大多数的开发在 Linux 下,多处用到进度条的场景,但又无需用到图形化界面,所以就想着弄个 console 下的进度条显示. 2 步骤 清行显示 //清行处理操作 int curren ...

  8. 小技巧:with用法 pycharm控制台输出带颜色的文字 打印进度条的

    with用法 with用法在python中是一个很独特的用法,因为别的语言的中没有这个用法.所以针对这个特点我们来做一次总结,什么样的情况下可以同with  我们学到的有文件的操作,和acquire  ...

  9. Ajax上传文件进度条显示

    要实现进度条的显示,就要知道两个参数,上传的大小和总文件的大小 html5提供了一个上传过程事件,在上传过程中不断触发,然后用已上传的大 小/总大小,计算上传的百分比,然后用这个百分比控制div框的显 ...

随机推荐

  1. 在虚拟机中安装Linux

    安装CentOS 6.4教程(详细步骤) CentOS是RHEL的克隆版本,功能上是一模一样的,另外重新编译之后还修复了一些后者的bug.主要区别就是CentOS免费,但没有官方的技术支持,而RHEL ...

  2. asp.net运行原理(一)总体概要

     1.浏览器发送请求报文到服务器,服务器接收到请求之后,根据请求报文头(url地址)的后缀名解析. 2.以iis服务器为例.他分为两种模式,经典模式和集成模式.主要是经典模式会将请求报文通过aspne ...

  3. Sql server 大全

    一.基础 .说明:删除数据库drop database dbname3.说明:备份sql server--- 创建 备份数据的 deviceUSE masterEXEC sp_addumpdevice ...

  4. batch 数字进制的问题

    when set viable to number type in cmdexample: set /a num=0833echo %num% display: Invalid number.  Nu ...

  5. IOS基础 Day-1手动内存管理

    辞职回家打算自学IOS开发,就在借个地方记录一下 Day-1      手动内存管理                   主要内容:release  retain必须配对好,不然会占用内存 慢慢积累导 ...

  6. ASP.NET MVC 路由进阶(之二)--自定义路由约束

    3.自定义路由约束 什么叫自定义路由约束呢?假如路由格式为archive/{year}/{month}/{day},其中year,month,day是有约束条件的,必须是数字,而且有一定范围. 这时候 ...

  7. FreeMarker-Built-ins for strings

    http://freemarker.org/docs/ref_builtins_string.html Page Contents boolean cap_first capitalize chop_ ...

  8. Guzz

    http://www.cnblogs.com/shitou/archive/2011/05/31/2064838.html

  9. qml自定义标题栏

    要实现自定义的标题栏只需在原来的窗口的基础上创建一个Rectangle并将其定位在窗口顶部即可,实现代码如下: ApplicationWindow { id: mainWindow visible: ...

  10. 【Sqlserver】修改数据库表中的数据:对缺失的数据根据已有的数据进行修补

    1 --查询时间范围内的数据 select * from dbo.point where wtime >'2014-05-01 23:59:59' and wtime< '2014-05- ...