您的位置:首页 > 编程语言 > C#

C#中使用aria2c进行下载并显示进度条

2016-08-18 09:21 871 查看
正则表达式的生成网站:

http://www.txt2re.com/index-csharp.php3

Program.cs

static void Main(string[] args)
{
var url =
"https://download.microsoft.com/download/E/4/1/E4173890-A24A-4936-9FC9-AF930FE3FA40/NDP461-KB3102436-x86-x64-AllOS-ENU.exe";

HttpDownLoad.DownloadFileByAria2(url, "c:\\NDP461-KB3102436-x86-x64-AllOS-ENU.exe");
Console.ReadLine();
}


RedirectRun.cs

using System.Diagnostics;

namespace ConsoleApplication1
{
public class RedirectRun
{
/// <summary>
/// 功能:重定向执行
/// </summary>
/// <param name="p"></param>
/// <param name="exe"></param>
/// <param name="arg"></param>
/// <param name="output"></param>
public static void RedirectExcuteProcess(Process p,string exe, string arg, DataReceivedEventHandler output)
{
p.StartInfo.FileName = exe;
p.StartInfo.Arguments = arg;

p.StartInfo.UseShellExecute = false;    //输出信息重定向
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;

p.OutputDataReceived += output;
p.ErrorDataReceived += output;

p.Start();                    //启动线程
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();            //等待进程结束
}
}
}


HttpDownLoad.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
public class HttpDownLoad
{

public static bool DownloadFileByAria2(string url, string strFileName)
{
var tool = AppDomain.CurrentDomain.BaseDirectory + "\\aria2-1.19.0\\aria2c.exe";
var fi = new FileInfo(strFileName);
var command = " -c -s 5 --check-certificate=false -d " + fi.DirectoryName + " -o " + fi.Name + " " + url;
Process _p;
using (_p = new Process())
{
RedirectRun.RedirectExcuteProcess(_p, tool, command, (s, e) => ShowInfo(e.Data));
}
return true;
}

public static void ShowInfo(string a)
{
if (a == null) return;

const string re1 = ".*?"; // Non-greedy match on filler
const string re2 = "(\\(.*\\))"; // Round Braces 1

var r = new Regex(re1+re2,RegexOptions.IgnoreCase|RegexOptions.Singleline);
var m = r.Match(a);
if (m.Success)
{
var rbraces1=m.Groups[1].ToString().Replace("(","").Replace(")","").Replace("%","");
if (rbraces1 == "OK")
{
rbraces1 = "100";
}
Console.WriteLine(rbraces1);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: