c# WebClient文件下载
2024-08-29 19:31:27
public void HttpDownload(string url, string path, ResourceType type)
{
using (var client = new WebClient())
{
client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var stream = client.OpenRead(url);
if (type == ResourceType.Document)
{
var header = client.ResponseHeaders["Content-Disposition"];
var subStr = header.Split('=');
var fileName = System.Web.HttpUtility.UrlDecode(subStr[1]);
path = GetFileValidation(path, fileName, out fileName);
}
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
ReadWriteStream(stream, writeStream);
}
}
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
//验证文件是否存在
public string GetFileValidation(string path, string oldTitle, out string newTitle)
{
string newPath = System.IO.Path.Combine(path, oldTitle.Replace("\"", ""));
string title1 = oldTitle; if (File.Exists(newPath))
{
for (int i = 1; i < int.MaxValue; i++)
{
newPath = System.IO.Path.Combine(path, oldTitle.Split('.')[0] + "(" + i + ")" + "." + oldTitle.Split('.')[1]);
if (!File.Exists(newPath))
{
title1 = oldTitle.Split('.')[0] + "(" + i + ")" + "." + oldTitle.Split('.')[1];
break;
}
else
{
continue;
}
}
}
newTitle = title1;
return newPath;
}
最新文章
- 161229、SpringMVC的各种参数绑定方式
- linux注销、关机、重启
- UART,USART,SPI,I2C等总线的介绍与区别20160526
- 短租app简析
- 解决eclipse中maven出现的Failure to transfer XXX.jar的问题
- Android手机定位技术的发展
- js控制文本框仅仅能输入中文、英文、数字与指定特殊符号
- java 泛型简单使用
- Redis进阶实践之八Lua的Cjson在Linux下安装、使用和用C#调用Lua脚本
- mybatis代码生成器
- 2018-09-13 代码翻译尝试-使用Roaster解析和生成Java源码
- nodejs静态web服务
- .Net Core 中间件之主机地址过滤(HostFiltering)源码解析
- Confluence 6 查看空间活动
- 线特征---EDLines原理(六)
- hudson运行出现java.io.IOException Cannot run program的错误分析
- LeetCode_Path Sum
- The 15th UESTC Programming Contest Preliminary M - Minimum C0st cdoj1557
- 在ZYNQ-7000平台上利用PS点亮PL上的LED灯
- Python 3基础教程17-提问频率较高的几个Python问题
热门文章
- KEIL中启动文件详解(汇编语言)
- iOS之触摸及手势
- js中A包含B的写法与分割字符串的方法
- SQL Server 2012安装错误案例:Error while enabling Windows feature: NetFx3, Error Code: -2146498298
- Windows下FFmpeg各版本库文件下载
- I2C基础知识
- RedHat6.2搭建FTP服务器
- nginx简易入门(转)
- 俄罗斯方块(Win32实现,Codeblocks+GCC编译)
- BZOJ 1070: [SCOI2007]修车 [最小费用最大流]