分类:
C#
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace Common { public class WebFileUpDown { /// <summary> /// WebClient上传文件至服务器 /// </summary> /// <param name="fileNamePath">文件名,全路径格式</param> /// <param name="uriString">服务器文件夹路径</param> /// <param name="IsAutoRename">是否自动按照时间重命名</param> public static void UpLoadFile(string fileNamePath, string NewName, string Weburl) { string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1); string NewFileName = NewName == "" ? fileName : NewName; string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1); if (Weburl.EndsWith("/") == false) Weburl = Weburl + "/"; Weburl = Weburl + NewFileName; /**/ /// 创建WebClient实例 WebClient myWebClient = new WebClient(); myWebClient.Credentials = System.Net.CredentialCache.DefaultCredentials; myWebClient.Credentials = CredentialCache.DefaultCredentials; // 要上传的文件 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(Weburl, "PUT"); try { if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); postStream.Close(); fs.Dispose(); } else { postStream.Close(); fs.Dispose(); } } catch (Exception err) { postStream.Close(); fs.Dispose(); throw err; } finally { postStream.Close(); fs.Dispose(); } } /// <summary> /// 下载服务器文件至客户端 /// </summary> /// <param name="URL">被下载的文件地址,绝对路径</param> /// <param name="Dir">另存放的目录</param> public static void Download(string URL, string Dir) { WebClient client = new WebClient(); string fileName = URL.Substring(URL.LastIndexOf("/") + 1); //被下载的文件名 string Path = Dir; //另存为的绝对路径+文件名 try { client.DownloadFile(URL, Path); } catch (Exception ex) { throw ex; } } } }
评价
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术