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

时间:2023-03-09 12:54:38
【转】C#中使用aria2c进行下载并显示进度条

【转自】

C#中使用aria2c进行下载并显示进度条 - 云平台知识库 - 博客园
https://www.cnblogs.com/littlehb/p/5782714.html

正则表达式的生成网站:

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

Aria2c下载地址:

https://github.com/aria2/aria2/releases/tag/release-1.34.0

保存的位置:程序运行目录/Download

Program.cs

        static void Main(string[] args)
{
var url = "http://dldir1.qq.com/weixin/Windows/WeChatSetup.exe";
if (url != "")
{
var fileName = url.Substring(url.LastIndexOf("/") + );
var r = HttpDownLoad.DownloadFileByAria2(url, string.Format("{0}\\Download\\{1}", Directory.GetCurrentDirectory(), fileName));
Console.WriteLine(r);
Console.ReadLine();
}
}

HttpDownLoad.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions; namespace ConsoleApplication2
{
public class HttpDownLoad
{
/// <summary>
/// 功能:使用Aria2c进行文件下载
/// 作者:黄海
/// 时间:2018-06-13
/// </summary>
/// <param name="url"></param>
/// <param name="strFileName"></param>
/// <returns></returns>
public static bool DownloadFileByAria2(string url, string strFileName)
{
var tool = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\aria2-1.34.0-win-64bit-build1\\aria2c.exe";
var fi = new FileInfo(strFileName);
var command = " -c -s 10 -x 10 --file-allocation=none --check-certificate=false -d " + fi.DirectoryName + " -o " + fi.Name + " " + url;
using (var p = new Process())
{
RedirectExcuteProcess(p, tool, command, (s, e) => ShowInfo(url,e.Data));
}
return File.Exists(strFileName) && new FileInfo(strFileName).Length>;
}
private static void ShowInfo(string url,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[].ToString().Replace("(", "").Replace(")", "").Replace("%", "").Replace("s","");
if (rbraces1 == "OK")
{
rbraces1 = "";
}
Console.WriteLine(DateTime.Now.ToString().Replace("/","-")+" "+url+" 下载进度:"+rbraces1+"%");
}
} /// <summary>
/// 功能:重定向执行
/// </summary>
/// <param name="p"></param>
/// <param name="exe"></param>
/// <param name="arg"></param>
/// <param name="output"></param>
private 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(); //等待进程结束
}
}
}