C# http方式下载文件,压缩文件
1、引入动态库ICSharpCode.SharpZipLib.Zip
2、代码 实现:
public class DownFileHelper
{
///
/// Http方式下载文件
///
/// http地址
/// 本地文件
///
public bool Download(string url, string localfile,out string message)
{
message = string.Empty;
bool flag = false;
long startPosition = 0;
// 上次下载的文件起始位置
FileStream writeStream;
// 写入本地文件流对象
string remoteFileLength = GetInfo(url);
if (Convert.ToDouble(remoteFileLength) <= 0 || remoteFileLength == "无法检测")
{
message = "远程文件不存在";
return false;
}
//long remoteFileLength = GetHttpLength(url);
// 取得远程文件长度
//Console.WriteLine("remoteFileLength=" + remoteFileLength);
//if (remoteFileLength == 745)
//{
//message="远程文件不存在";
//return false;
//}
//判断要下载的文件夹是否存在
if (File.Exists(localfile))
{
File.Delete(localfile);
writeStream = new FileStream(localfile, FileMode.Create);
// 文件不保存创建一个文件
startPosition = 0;
}
else
{
writeStream = new FileStream(localfile, FileMode.Create);
// 文件不保存创建一个文件
startPosition = 0;
}
try
{
HttpWebRequest myRequest = (HttpWebRequest) WebRequest.Create(url);
// 打开网络连接
if (startPosition > 0)
{
myRequest.AddRange((int) startPosition);
// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
}
Stream readStream = myRequest.GetResponse().GetResponseStream();
// 向服务器请求,获得服务器的回应数据流
byte[] btArray = new byte[512];
// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
int contentSize = readStream.Read(btArray, 0, btArray.Length);
// 向远程文件读第一次
while (contentSize > 0) // 如果读取长度大于零则继续读
{
writeStream.Write(btArray, 0, contentSize);
// 写入本地文件
contentSize = readStream.Read(btArray, 0, btArray.Length);
// 继续向远程文件读取
}
writeStream.Close();
readStream.Close();
flag = true;
//返回true下载成功
}
catch (Exception exception)
{
writeStream.Close();
Trace.Write($"Http方式下载文件失败:{exception.Message}");
message = $"下载数据文件失败:{exception.Message}";
flag = false;
//返回false下载失败
}
return flag;
}
publicstring GetInfo(string URL)
{
string Results = "";
long ContentL = 0;
if (URL.ToLower().StartsWith("https://"))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
ContentL = response.ContentLength;
response.Close();
Results += GetSize(ContentL);
}
else if (URL.ToLower().StartsWith("ftp://"))
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(URL);
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.UseBinary = true;
FtpWebResponse response = null;
response = (FtpWebResponse)request.GetResponse();
Stream Fs = response.GetResponseStream();
ContentL = response.ContentLength;
Fs.Close();
response.Close();
Results += GetSize(ContentL);
}
else
{
Results += "无法检测";
}
return Results;
}
//大小转化
publicstring GetSize(long L)
{
float result;
//string re = "";
if (L >= 1073741824)
{
result = L / 1073741824.00F;
//re = "GB";
}
else if (L >= 1048576)
{
result = L / 1048576.00F;
//re = "MB";
}
else
{
result = L / 1024.00F;
//re = "KB";
}
string File_Size = result.ToString("0.00");
return File_Size;
}
///
/// 从文件头得到远程文件的长度
///
///
///
private long GetHttpLength(string url)
{
long length = 0;
try
{
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url);
HttpWebResponse rsp = (HttpWebResponse) req.GetResponse();
if (rsp.StatusCode == HttpStatusCode.OK)
{
length = rsp.ContentLength;
}
rsp.Close();
return length;
}
catch (Exception ex)
{
Trace.Write("从文件头得到远程文件的长度出现错误:" + ex.Message);
return length;
}
}
///
/// 解压文件
///
/// 解压文件路径
/// 解压到文件夹的名称
///
public bool ZipToFile(string zipName, string fileDirName,out string message)
{
message = string.Empty;
try
{
//读取压缩文件(zip文件),准备解压缩
ZipInputStream s = new ZipInputStream(File.Open(zipName.Trim(), FileMode.Open, FileAccess.Read));
ZipEntry theEntry;
string rootDir = " ";
while ((theEntry = s.GetNextEntry()) != null)
{
string path = fileDirName;
//获取该文件在zip中目录
rootDir = Path.GetDirectoryName(theEntry.Name);
//获取文件名称
string fileName = Path.GetFileName(theEntry.Name);
if (string.IsNullOrEmpty(fileName))
{
continue;
}
//判断是否为顶层文件,是,将文件直接放在fileDirName下,否,创建目录
if (string.IsNullOrEmpty(rootDir))
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
else
{
path += "\\" + rootDir;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
//将文件流写入对应目录下的文件中
if (fileName != string.Empty)
{
FileStream streamWriter = File.Create(path + "\\" + fileName);
int size = 2048;
byte[] data = https://www.it610.com/article/new byte[2048];
while (true)
{
if (theEntry.Size == 0)
{
break;
}
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
return true;
}
catch (Exception ex)
{
Trace.Write("解压过程出现异常:" + ex.Message);
message = "解压过程出现异常:" + ex.Message;
return false;
}
}
}
3、 调用
DownFileHelper downFileHelper = new DownFileHelper();
if (downFileHelper.Download(result.Data.ToString(), CommonUtil.GetCurrentDirectory() + @"temp.zip", out string message))
{
if (!downFileHelper.ZipToFile(CommonUtil.GetCurrentDirectory() + @"temp.zip", CommonUtil.GetCurrentDirectory(), out message))
{
DialogHelper.ShowInfo("提示", "解压打印数据失败:" + message, "确定");
Trace.Write("解压打印数据失败:" + message);
return;
}
}
else
{
DialogHelper.ShowInfo("提示", "下载打印数据失败:" + message, "确定");
Trace.Write("下载打印数据失败:" + message);
return;
【C# http方式下载文件,压缩文件】}
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- mybatisplus|mybatisplus where QueryWrapper加括号嵌套查询方式
- 画解算法(1.|画解算法:1. 两数之和)
- ts泛型使用举例
- https请求被提早撤回
- 10.两种记账方式
- 《机器学习实战》高清中文版PDF英文版PDF+源代码下载
- 百度云极速下载,来体验飞的感觉,还可以看最新动漫的百度云视频哦
- HTTP高级(Cookie,Session|HTTP高级(Cookie,Session ,LocalStorage )
- 拒绝可以很艺术,或者很行为艺术。