目前相对稳定的下载上传的方法(WebClient )(异步与进度)

news/2024/9/29 21:24:47/

使用webdav (WebClient ) 操作另外还有其他方法:
上传操作

/// <summary>/// 上传大文件使用的方法/// </summary>/// <param name="FileName">文件当前路径</param>/// <returns>msg.ReturnStr 返回上传文件地址</returns>public  CommMsg   UploadByBigFileweb(string FileName)// CommMsg UploadByBigFileweb(string FileName){string ThisFenqu = DateTime.Now.ToString("yyyy-MM");string DirPath = WebDirAll + $"{ThisFenqu}/";Uri myURi = new System.Uri(DirPath + Path.GetFileName(FileName));// 创建WebClient实例WebClient myWebClient = new WebClient();//访问权限设置      myWebClient.Credentials = new NetworkCredential(WebUser, WebPw);try{FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);BinaryReader br = new BinaryReader(fs);byte[] postArray = br.ReadBytes((int)fs.Length);myWebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressChangd);myWebClient.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadeCompleteZd);myWebClient.UploadFileAsync(myURi,"PUT", FileName);//必须加入条件PUTif (FrmPreB == null){FrmPreB = new FrmPressBar();}FrmPreB.Show();FrmPreB.SetFileName = FileName;FrmPreB.SetPressMaxValue = (int)fs.Length;//while (!IsUploadSuc)//{//    await Task.Delay(1000);//} msg.ReturnStr = ThisFenqu + "/" + Path.GetFileName(FileName);msg.Success = true; }catch (WebException errMsg){if (errMsg.Message.Contains("(409)"))//如果失败就创建文件夹后才重新操作{CommMsg msgThis = new CommMsg();msgThis = CreateDir(DirPath);if (msg.Success){UploadByweb(FileName);}else{msg.Success = false;msg.ErrMsg = "文件夹创建失败";}}else{msg.Success = false;msg.ErrMsg = errMsg.Message;}}return msg;}/// <summary>/// 上传结束了/// </summary>/// <param name="Sender"></param>/// <param name="e"></param>private void UploadeCompleteZd(object Sender, UploadFileCompletedEventArgs e){this.DialogResult = DialogResult.OK;}/// <summary>/// 上传进度操作/// </summary>/// <param name="Sender"></param>/// <param name="e"></param>private void UploadProgressChangd(object Sender, UploadProgressChangedEventArgs e){if (this.IsHandleCreated){this.SetFilelengthValue = (int)e.TotalBytesToSend;this.SetFilelengthThisValue = (int)e.BytesSent;}}/// <summary>/// 两秒以后开启操作(如果在frm界面上操作的话)/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void timer1_Tick(object sender, EventArgs e){OutMsg =  UploadByBigFileweb(FileNameAdd);timer1.Stop();}

下载操作

  /// <summary>/// 下载数据直接保存到地址(外部下载使用)/// </summary>/// <param name="FileNameAndYearMonth">服务器地址</param>/// <param name="SetPath">设置路径的操作,如果没有就是默认的LocalDir</param>/// <returns></returns>public CommMsg DownloadFileToPath(string FileNameAndYearMonth, string SetPath = ""){try{//string FileName = FileNameAndYearMonth.Substring(FileNameAndYearMonth.IndexOf("/") + 1);string FileWebName = FileNameAndYearMonth.Replace("\\", "/").Replace("\\\\", "/");string SaveFileurl;if (string.IsNullOrWhiteSpace(SetPath))//如果是空就是默认路径{SaveFileurl = LocalDir + FileNameAndYearMonth.Replace("/", "\\");}else{SaveFileurl = SetPath;}FileInfo Finfo = new FileInfo(SaveFileurl);if (File.Exists(SaveFileurl)){msg.Success = true;msg.ErrMsg = "文件已存在!";msg.ReturnStr = SaveFileurl;}else{if (!Finfo.Directory.Exists){Finfo.Directory.Create();}string GetFileurl = WebDirAll + FileWebName;WebClient client = new WebClient();client.Credentials = new NetworkCredential(WebUser, WebPw);Uri FileWebUri = new Uri(GetFileurl);client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChangd);client.DownloadDataCompleted +=  new DownloadDataCompletedEventHandler(DownloadFileCompleteZ);if (FrmPreB == null){FrmPreB = new FrmPressBar();}FrmPreB.Show();FrmPreB.SetFileName = SaveFileurl;client.DownloadFileAsync(FileWebUri, SaveFileurl);//client.DownloadFile(GetFileurl, SaveFileurl);msg.Success = true;msg.ReturnStr = SaveFileurl;}}catch (Exception ex){msg.Success = false;msg.ErrMsg = ex.Message;}return msg;}/// <summary>/// 下载页面/// </summary>/// <param name="Sender"></param>/// <param name="e"></param>private void DownloadProgressChangd(object Sender, DownloadProgressChangedEventArgs e){if (FrmPreB.IsHandleCreated){FrmPreB.SetFilelengthValue = (int)e.TotalBytesToReceive;FrmPreB.SetFilelengthThisValue = (int)e.BytesReceived;}}/// <summary>/// 下载完成面/// </summary>/// <param name="Sender"></param>/// <param name="e"></param>private void DownloadFileCompleteZ(object Sender, DownloadDataCompletedEventArgs e){IsDownLoadSuc = true;}

单独需要from支持的情况下需要的数据:

 string WebDirAll = "";//全部路劲string LocalDir = Environment.CurrentDirectory + "\\WebTemp\\";string WebBaseDir = CommParameter.Url + "/" + CommParameter.DirName + "/";CommMsg msg = new CommMsg();string WebAdd = "";//ftp地址string WebUser = "";//ftp用户string WebPw = "";//ftp密码string WebDir = "";//ftp文件夹   /// <summary>/// 设置进度条最大位置/// </summary>private int _SetPressMaxValue;public int SetPressMaxValue{get{return _SetPressMaxValue;}set{_SetPressMaxValue = value; }}/// <summary>/// 设置进度条最小位置/// </summary>private int _SetPressMinValue;public int SetPressMinValue{get{return _SetPressMinValue;}set{_SetPressMinValue = value;this.Invoke(new Action(() =>{this.ThisPressDown.Minimum = 0;}));}}/// <summary>///  /// 设置文件大小 /// </summary>public int _SetFilelengthValue;public int SetFilelengthValue{get { return _SetFilelengthValue; }set{_SetPressMaxValue = value;_SetFilelengthValue = value;this.Invoke(new Action(() =>{this.ThisPressDown.Maximum = value;}));}}private int _SetFilelengthThisValue;/// <summary>/// 设置当前下载或者上传到达位置/// </summary>public int SetFilelengthThisValue{get{return _SetFilelengthThisValue;}set{_SetFilelengthThisValue = value;this.Invoke(new Action(() =>{ThisPressDown.Value = SetFilelengthThisValue;LBPressA.Text = $"当前进度:{SetFilelengthThisValue / 1024}K/{SetFilelengthValue / 1024}K";}));}}private string  _SetFileName;/// <summary>/// 设置当前文件名称/// </summary>public string SetFileName{get{return _SetFileName;}set{_SetFileName = value;this.Invoke(new Action(() =>{LBFilename.Text =value;}));}}/// <summary>/// 设置当前文件名称/// </summary>private string _SetPreeRemark;public string SetPreeRemark{get{return _SetPreeRemark;}set{_SetPreeRemark = value;this.Invoke(new Action(() =>{LBPressA.Text = $"当前进度:{SetFilelengthThisValue/1024}K/{SetFilelengthThisValue/1024}K" ;}));}}string FileNameAdd;public CommMsg OutMsg;public FrmUploadFile( string FileNameAddin){InitializeComponent();FileNameAdd = FileNameAddin;WebAdd = CommParameter.Url;WebUser = CommParameter.UserName;WebPw = CommParameter.Pwd;WebDir = CommParameter.DirName;List<string> DirList = new List<string> { WebBaseDir, WebBaseDir + "Pic/", WebBaseDir + "File/", WebBaseDir + "Media/" };if (!Directory.Exists(LocalDir)){Directory.CreateDirectory(LocalDir);}if (string.IsNullOrEmpty(WebAdd) || string.IsNullOrEmpty(WebUser) || string.IsNullOrEmpty(WebPw)){throw new Exception("Ftp配置有问题,请在配置文件config下关于FTP所有的参数。");}else//获取全部路径{switch (CommParameter.SetType){case FileType.图片:WebDirAll = WebBaseDir + "Pic/";break;case FileType.文档:WebDirAll = WebBaseDir;break;case FileType.音视频:WebDirAll = WebBaseDir + "Media/";break;default:WebDirAll = WebBaseDir;break;}}//OutMsg = UploadByBigFileweb(FileNameAdd);timer1.Start();}

调用方式:

FrmUploadFile frmUp = new FrmUploadFile(Openfile.FileName); 

show 或者 frmUp.ShowDialog()==OK都可以。为了界面可以展示开,定时2s开始下载或者上传数据。

另外其他的使用方法:

using (WebClient client = new WebClient()){string fileName = openFileDialog1.FileName;Uri url_upload = new Uri("change recive remote url");NameValueCollection nvc = new NameValueCollection();// data insert// nvc.Add("userid", "user01");// nvc.Add("workid", "work01");client.QueryString = nvc;client.UploadFileCompleted += (s, e1) =>{string msg;btn_Selectfile.Enabled = true;btn_Upload.Enabled = true;msg = Encoding.UTF8.GetString(e1.Result);MessageBox.Show(msg);};client.UploadProgressChanged += (s, e1) =>{double BytesSent = e1.BytesSent;double TotalBytesToSend = e1.TotalBytesToSend;int percent = (int)((BytesSent / TotalBytesToSend) * 100.0);prog_Upload.Value = percent;lbl_Percent.Text = percent + "%";};client.UploadFileAsync(url_upload, fileName);client.Dispose();}

FTP上传方法:

using (var request = new WebClient())
{request.Credentials = DefaultCredentials;try{request.UploadFileAsync(new Uri($"ftp://{ServerAddress}/{outfilepath}"), "STOR", infilepath);return true;}catch (WebException ex){Logger.Write(ex.Message);return false;}}

http://www.ppmy.cn/news/1532093.html

相关文章

浅谈软件安全开发的重要性及安全开发实践

在当今数字化时代&#xff0c;软件已成为企业运营的核心驱动力。然而&#xff0c;随着网络环境的日益复杂和黑客技术的不断演进&#xff0c;软件安全问题日益凸显&#xff0c;成为企业不可忽视的重大挑战。本文将从法律法规要求、企业核心数据资产保护、企业信誉等角度&#xf…

【逐行注释】MATLAB的程序,对比EKF(扩展卡尔曼滤波)和PF(粒子滤波)的滤波效果,附下载链接

文章目录 总述部分源代码运行结果扩展性 总述 本代码使用 M A T L A B MATLAB MATLAB实现了扩展卡尔曼滤波&#xff08; E K F EKF EKF&#xff09;和粒子滤波&#xff08; P F PF PF&#xff09;在状态估计中的对比分析。 主要功能包括&#xff1a; 参数设置&#xff1a;初始…

企业微信:客户联系自带群发工具和聊天工具

前言 上篇博客介绍了一些客户联系的开启和配置&#xff0c;接下来我们来使用客户联系自带群发工具和聊天工具。 突然发现官方的文档已经很详细了&#xff0c;我这里给出一些简单的描述&#xff1a; 企业微信如何使用群发助手&#xff1f;-帮助中心-企业微信 群发工具 群发消息给…

Linux2.6* 内核默认支持的文件系统

Linux2.6* 内核默认支持的文件系统 Btrfs是一种具有先进特性的写时复制文件系统。支持多种高级功能&#xff0c;如快照、透明压缩、数据校验和自我修复等&#xff0c;适用于大规模存储系统和数据可靠性要求较高的场景。JFSJournaled File System日志文件系统&#xff0c;具有高…

uniapp view设置当前view之外的点击事件

推荐学习文档 golang应用级os框架&#xff0c;欢迎stargolang应用级os框架使用案例&#xff0c;欢迎star案例&#xff1a;基于golang开发的一款超有个性的旅游计划app经历golang实战大纲golang优秀开发常用开源库汇总想学习更多golang知识&#xff0c;这里有免费的golang学习笔…

怎么用gitee做一个图片仓库,在md文档中用这个图片网络地址,然后显示图片

痛因&#xff1a;我为什么要这样做&#xff0c;呃&#xff0c;我一开始图片都是存本地地址的&#xff0c;放在和这个md文档同级的assets文件夹下面&#xff0c;这样子确实当时很方便&#xff0c;复制粘贴什么也不用管&#xff0c;但是想把这个文档分享给别的人的时候&#xff0…

9月27日,每日信息差

第一、中国科学家团队在干细胞治疗领域取得重要突破&#xff0c;通过化学重编程技术成功制备出胰岛细胞&#xff0c;并用于移植治疗一名 1 型糖尿病患者&#xff0c;实现了临床功能性治愈。相关研究成果已发表在国际权威期刊《细胞》上。 第二、交通运输部公路局局长周荣峰在国…

路由器的天线有什么用?数量多≠信号强?

你是否也曾凝视着路由器上那几根或长或短的天线&#xff0c;心中暗自嘀咕&#xff1a;“这些天线到底有啥用&#xff1f;是不是天线越多&#xff0c;信号就越强呢&#xff1f;”今天&#xff0c;让我们一同揭开这一谜团&#xff01; 一、路由器天线的核心作用 1. 信号发射与接…