用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框的显 ...
随机推荐
- Web.config加密和解密
在系统部署的时候,大家都会遇到关于用户凭证的安全性问题,而对于数据库连接的相关的信息,有些时候客户也需要我们对其加密,防止信息泄露,在此将加密和解的方法记录于此: 首先用管理员的权限启动cmd命令窗口 ...
- tools安装
1.ruby安装 下载安装包 勾选中间一个 2.sass 安装 转换TB镜像 $ gem sources --remove https://rubygems.org/$ gem sources - ...
- css3 多列布局记
css3 多列布局 多列布局属性: columns:column-widht和column-count的缩写. column-width:定义每列列宽度. column-count:定义分列列数. c ...
- PS基础学习 2---图层蒙版
1,蒙版,字面意思上的理解就是:把底层图片上面加上一层图层蒙着,通过画笔工具控制底层图片和上面一层图层的显示效果.常用于图层的无缝隙合成. 我们可以先看一下下面的这个小例子,这个就是蒙版的一个小应用: ...
- Jersey(1.19.1) - Conditional GETs and Returning 304 (Not Modified) Responses
Conditional GETs are a great way to reduce bandwidth, and potentially server-side performance, depen ...
- MyBatis(3.2.3) - Passing multiple input parameters
MyBatis's mapped statements have the parameterType attribute to specify the type of input parameter. ...
- 使用Win7+IIS7发布网站或服务步骤
1.安装IIS服务:控制面板=>程序=>打开或关闭WINDOWS 功能=>Internet 信息服务=>WEB服务管理器全选√ 和万维网服务:应用程序开发功能: 2.打开IIS ...
- JAVA生成EXCEL图表
跟据客户的要求,需要开发一套包括图形的报表,还需要导出WORD 图表需要这样: 这样: 这样: 还有这样: 接下来是实现思路: 以往用的最多的就是JFreechart,手上也有实现各种图形的资源,但是 ...
- JSON解析保存在类中
//my.h#ifndef __1_Header_h#define __1_Header_h#define DEBUG 1#define aa 1 #ifdef aa#ifdef DEBUG#defi ...
- OC8_setter方法展开
// // Person.h // OC8_setter方法展开 // // Created by zhangxueming on 15/6/18. // Copyright (c) 2015年 zh ...