📒博客首页:蔚说的博客 |
---|
🎉欢迎关注🔎点赞👍收藏⭐️留言📝 |
🙏作者水平很有限,如果发现错误,求告知,多谢! |
🌺有问题可私信交流!!! |
(C#学习笔记)仅供学习交流 |
C#通过URl批量下载&打包压缩-重难点 C#通过URl批量下载&打包压缩引用的类实例 |
** 实现解压缩功能公用类。 using ICSharpCode.SharpZipLib.Zip**
using ICSharpCode.SharpZipLib.Zip;
下载地址:https://download.csdn.net/download/opinion001/87727030
** 参数List HttpUrlList 是一个包含URL的list数组 file_name 是打包zip包的名称 filePath 是下载zip包的位置 返回值 1.成功 2.否则是报错信息 **
public string DownloadFileByHttpUrl(List<string> HttpUrlList)
{
if (HttpUrlList == null || HttpUrlList.Count == 0)
{
return null;
}
try
{
var random = new Random();
var zipMs = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(zipMs);
zipStream.SetLevel(9);//压缩率0~9
foreach (var url in HttpUrlList)
{
if (!string.IsNullOrWhiteSpace(url))
{
var urlStr = HttpUtility.UrlDecode(url);
Console.WriteLine(urlStr);
string fileExt = Path.GetExtension(urlStr).ToLower();
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(urlStr);
var strName = fileNameWithoutExtension.Substring(fileNameWithoutExtension.LastIndexOf("/") + 1) + random.Next(1000, 9999) + fileExt;
zipStream.PutNextEntry(new ZipEntry(strName));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlStr);
request.AllowAutoRedirect = true;
WebProxy proxy = new WebProxy();
proxy.BypassProxyOnLocal = true;
proxy.UseDefaultCredentials = true;
request.Proxy = proxy;
WebResponse response = request.GetResponse();
using (Stream streams = response.GetResponseStream())
{
Byte[] buffer = new Byte[1024];
int current = 0;
while ((current = streams.Read(buffer, 0, buffer.Length)) != 0)
{
zipStream.Write(buffer, 0, current);
}
zipStream.Flush();
}
}
}
zipStream.Finish();
zipMs.Position = 0;
//下边为打包压缩
MemoryStream stream = zipMs;
byte[] srcBuf = new Byte[stream.Length];
stream.Read(srcBuf, 0, srcBuf.Length);
stream.Seek(0, SeekOrigin.Begin);
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string date = DateTime.Now.ToString("yyyyMMddHHmmss");
var file_name = "全电发票" + date + ".zip";
using (FileStream fs = new FileStream(filePath + "\\" + file_name, FileMode.Create, FileAccess.Write))
{
fs.Write(srcBuf, 0, srcBuf.Length);
fs.Close();
return "下载成功";
}
}
catch (Exception ex)
{
return ex.ToString();
}
}