当前位置:网站首页>C# 文件下载方式
C# 文件下载方式
2022-06-23 12:02:00 【大老婆灰原哀】
public class RemoteDownload
{
public static void DownLoad(string addressUrl,string localName)
{
//下载文件
System.NET.WebClient myWebClient = new System.Net.WebClient();
myWebClient.DownloadFile(@"/10.2.0.254/software/01279.lic.txt", "testdownload.txt");
//下载end
}
}
通过URL获取页面内容
try
{
// 远程获取目标页面源码
string strTargetHtml = string.Empty;
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
byte[] btPageData = wc.DownloadData(strTargetUrl + dtTargetDate.ToString("yyyy") + "/" + dtTargetDate.ToString("MM") + "/" + dtTargetDate.ToString("dd") + "/");
strTargetHtml = Encoding.UTF8.GetString(btPageData);
wc.Dispose();
}
catch(Exception exp)
{
_isError = true;
_errorDetail = "获取目标日志文件列表时出错:" + exp.Message;
}
通过web方式,从远程服务器端下载文件:
public class WebDownload
{
public static void DownLoad(string Url, string FileName)
{
bool Value = false;
WebResponse response = null;
Stream stream = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
response = request.GetResponse();
stream = response.GetResponseStream();
if (!response.ContentType.ToLower().StartsWith("text/"))
{
Value = SaveBinaryFile(response, FileName);
}
}
catch (Exception err)
{
string aa = err.ToString();
}
}
/// <summary>
/// Save a binary file to disk.
/// </summary>
/// <param name="response">The response used to save the file</param>
// 将二进制文件保存到磁盘
private static bool SaveBinaryFile(WebResponse response, string FileName)
{
bool Value = true;
byte[] buffer = new byte[1024];
try
{
if (File.Exists(FileName))
File.Delete(FileName);
Stream outStream = System.IO.File.Create(FileName);
Stream inStream = response.GetResponseStream();
int l;
do
{
l = inStream.Read(buffer, 0, buffer.Length);
if (l > 0)
outStream.Write(buffer, 0, l);
}
while (l > 0);
outStream.Close();
inStream.Close();
}
catch
{
Value = false;
}
return Value;
}
从FTP上下载文件:
public class FtpDownload
{
public static void DownLoad(string FtpPath)
{
/*首先从配置文件读取ftp的登录信息*/
string TempFolderPath = System.Configuration.ConfigurationManager.AppSettings["TempFolderPath"].ToString();
string FtpUserName = System.Configuration.ConfigurationManager.AppSettings["FtpUserName"].ToString();
string FtpPassWord = System.Configuration.ConfigurationManager.AppSettings["FtpPassWord"].ToString();
string LocalFileExistsOperation = System.Configuration.ConfigurationManager.AppSettings["LocalFileExistsOperation"].ToString();
Uri uri = new Uri(FtpPath);
string FileName = Path.GetFullPath(TempFolderPath) + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(uri.LocalPath);
//创建一个文件流
FileStream fs = null;
Stream responseStream = null;
try
{
//创建一个与FTP服务器联系的FtpWebRequest对象
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
//设置请求的方法是FTP文件下载
request.Method = WebRequestMethods.Ftp.DownloadFile;
//连接登录FTP服务器
request.Credentials = new NetworkCredential(FtpUserName, FtpPassWord);
//获取一个请求响应对象
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//获取请求的响应流
responseStream = response.GetResponseStream();
//判断本地文件是否存在,如果存在,则打开和重写本地文件
if (File.Exists(FileName))
{
if (LocalFileExistsOperation == "write")
{
fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);
}
}
//判断本地文件是否存在,如果不存在,则创建本地文件
else
{
fs = File.Create(FileName);
}
if (fs != null)
{
int buffer_count = 65536;
byte[] buffer = new byte[buffer_count];
int size = 0;
while ((size = responseStream.Read(buffer, 0, buffer_count)) > 0)
{
fs.Write(buffer, 0, size);
}
fs.Flush();
fs.Close();
responseStream.Close();
}
}
finally
{
if (fs != null)
fs.Close();
if (responseStream != null)
responseStream.Close();
}
}
}
边栏推荐
- 蓝桥杯单片机(一)——关闭外设及熄灭LED
- 【无标题】2022年压力管道巡检维护试题及在线模拟考试
- TT-SLAM:用于平面环境的密集单目SLAM(IEEE 2021)
- Analysis of six dimensional chart: analysis of enterprise growth of CSCEC
- Qt知识:视图框架QGraphicsWidget详解
- Unity学习Day14--协程和WWW
- halcon原理:相关性匹配
- record
- Halcon knowledge: dyn_ Usage of threshold (scratch detection)
- CRMEB知识付费如何二开阿里云短信功能
猜你喜欢

“梦想童行” 2022年广汽本田儿童道路安全公益行走进东北

Linked list 5 - 234 Palindrome linked list

Huawei cloud gaussdb heavily released HTAP for commercial use, defining a new paradigm of cloud native database 2.0

蓝桥杯单片机(一)——关闭外设及熄灭LED

"Dream of children's travel" in 2022, GAC Honda children's road safety charity travel entered the Northeast

Localization information | aikesheng and China kefangde complete product compatibility and mutual certification

With 32 qubits! Rigetti computing enters the UK quantum computing market

Meta said that the UK security law may "scan all private information" or infringe privacy

二維激光SLAM( 使用Laser Scan Matcher )

The median annual salary exceeds 300000, and the salary of the first AI major graduate of Nanjing University is exposed
随机推荐
Design of routing service for multi Activity Architecture Design
AssetBundle资源管理
Open classes are short videos! Tonight, I will teach you how to realize accurately!
QT知识:Qt Widgets小部件类【01】
Halcon principle: correlation matching
[cloud native & microservice viii] source code analysis of weightedresponsetimerule of ribbon load balancing strategy (response time weighting)
WC statistics are out of date, and every line of cloc code is valid
Wallys/DR6018-S/ 802.11AX MU-MIMO OFDMA / 2* GE PORTS/WIFI 6e / BAND DUAL CONCURRENT
Deveco device tool helps openharmony device development
DuPont analysis: what is the investment value of Anyang Iron and Steel Co., Ltd?
ROS observation [51]: how to integrate odometer and IMU with robots_ Localization convergence
Introduction to redis - Chapter 3 - data structures and objects - Dictionary
ROS2知识(1):开始实践机器人
六维图剖析:中国建筑集团有限公司企业成长性分析
[zero foundation wechat applet] actual development of ID photo changing background color applet based on Baidu brain portrait segmentation
Simulation questions and answers of the latest national fire-fighting facility operators (primary fire-fighting facility operators) in 2022
[basic knowledge] - data bit width converter
ROS2知识(6):坐标对象TF原理和实践
LinkedList 5-141. 环形链表
QT knowledge: QT widgets widget function [02]