- WebClient:
1 /// <summary> 2 /// WebClient上传文件至服务器(不带进度条) 3 /// </summary> 4 /// <param name="localFilePath">要上传的文件(全路径格式)</param> 5 /// <param name="targetFolder">Web服务器文件夹路径</param> 6 /// <returns>True/False是否上传成功</returns> 7 public static void UpLoadFile(string localFilePath, string targetFolder) 8 { 9 //get file name 10 string fileName = Path.GetFileName(localFilePath); 11 if (string.IsNullOrEmpty(fileName)) 12 { 13 throw new InvalidOperationException("the file name is empty"); 14 } 15 //get target url 16 string targetUrl = Path.Combine(targetFolder, fileName); 17 18 WebClient webClient = null; 19 FileStream myFileStream = null; 20 BinaryReader myBinaryReader = null; 21 Stream writeStream = null; 22 23 try 24 { 25 webClient = new WebClient(); 26 //初始化读取数据流 27 myFileStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read); 28 myBinaryReader = new BinaryReader(myFileStream); 29 byte[] postArray = myBinaryReader.ReadBytes((int)myFileStream.Length); 30 //打开远程Web地址,将文件流写入 31 writeStream = webClient.OpenWrite(targetUrl, "PUT"); 32 writeStream.Write(postArray, 0, postArray.Length); 33 } 34 finally 35 { 36 if (writeStream != null) { writeStream.Close(); } 37 if (myBinaryReader != null) { myBinaryReader.Close(); } 38 if (myFileStream != null) { myFileStream.Close(); } 39 if (webClient != null) { webClient.Dispose(); } 40 } 41 } 42 43 /// <summary> 44 /// 下载服务器文件至客户端 45 /// </summary> 46 /// <param name="strUrlFilePath">要下载的Web服务器上的文件地址</param> 47 /// <param name="strLocalDirPath">存放下载文件的本地目录</param> 48 /// <returns>True/False是否上传成功</returns> 49 public static void DownLoadFile(string strUrlFilePath, string strLocalDirPath) 50 { 51 //get file name 52 string fileName = Path.GetFileName(strUrlFilePath); 53 if (string.IsNullOrEmpty(fileName)) 54 { 55 throw new InvalidOperationException("the file name is empty"); 56 } 57 58 //判断本地目录是否存在,如不存在,则创建新目录 59 if (!Directory.Exists(strLocalDirPath)) 60 { 61 Directory.CreateDirectory(strLocalDirPath); 62 } 63 64 string localFilePath = Path.Combine(strLocalDirPath, fileName); 65 66 using (var client = new WebClient()) 67 { 68 client.DownloadFile(strUrlFilePath, localFilePath); 69 } 70 }
相关文章: