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

    1012: [JSOI2008]最大数maxnumber Time Limit: 3 Sec  Memory Limit: 162 MBSubmit: 7912  Solved: 3441[Submi ...

  2. Django学习--9 Admin

    1.vim settings.py 打开  'django.contrib.admin' vim urls.py 打开 from django.contrib import admin     (注意 ...

  3. iPad accessory communication through UART

    We manufacture a new accessory for iPad/iPhone which should transfer commands to the iPad. We like t ...

  4. Oracle中存储过程传入表名学习

    Oracle中存储过程传入表名: 一.动态清除该表的数据 create or replace procedure p_deletetable(i_tableName in varchar2)  as  ...

  5. 当html中存在url中如: onclick="toView('参数1')", 参数1是特别字符,如&asop;&quot;' "等时,浏览器解析时会报错。解决方法如文中描述

    解决方案: 自定义标签将字符串转换成unicode编码后输出显示到页面即可 解析原理:解析顺序html  ---url ----javascript---url,由于unicode编码在htm解析阶段 ...

  6. Sublime Text 3初体验之Package Control

    http://www.imooc.com/article/12616 下面介绍几款Sublime Text 常用Package 1.Emmit 2.JavaScript & NodeJS Sn ...

  7. css设置网页打印样式

    有三种方法 1. 为屏幕显示和打印分别准备一个css文件,如下所示:  用于屏幕显示的css: <link rel="stylesheet" href="css/n ...

  8. Item47

    STL迭代器分类:input迭代器.output迭代器.forward迭代器.bidirectional迭代器.random access迭代器. Input迭代器:只能向前移动,一次一步,客户只读取 ...

  9. 函数 sort,unique,stable_sort,count_if,谓词

    bool isShorter(const string &s1,const string &s2) { return s1.size() < s2.size(); } bool ...

  10. bzoj 1023: [SHOI2008]cactus仙人掌图

    这道题是我做的第一道仙人掌DP,小小纪念一下…… 仙人掌DP就是环上的点环状DP,树上的点树上DP.就是说,做一遍DFS,DFS的过程中处理出环,环上的点先不DP,先把这些换上的点的后继点都处理出来, ...