C# winform通过WebClient上传文件至服务器

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Windows.Forms; namespace UI { public class WinFileTransporter { ///

/// WebClient上传文件至服务器,默认不自动改名 /// /// 文件名,全路径格式 /// 服务器文件夹路径 public void UpLoadFile(string fileNamePath,string urlString) { UpLoadFile(fileNamePath,urlString,false); } /// /// WebClient上传文件至服务器 /// /// 文件名,全路径格式 /// 服务器文件夹路径 /// 是否自动按照时间重命名 public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename) { string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("//")+1); string newFileName = fileName; if (IsAutoRename) { newFileName = DateTime.Now.ToString("yyMMddhhmmss")+DateTime.Now.Millisecond.ToString()+fileNamePath.Substring(fileNamePath.LastIndexOf(".")); } string fileNameExt = fileName.Substring(fileName.LastIndexOf(".")+1); if (uriString.EndsWith("/")==false) uriString = uriString + "/"; uriString = uriString + newFileName; WebClient myWebClient = new WebClient(); //设置应用程序的系统凭据 myWebClient.Credentials = CredentialCache.DefaultCredentials; //要上传的文件穿件文件流 FileStream fs = new FileStream(fileNamePath,FileMode.Open,FileAccess.ReadWrite); //以二进制方式读取 BinaryReader br = new BinaryReader(fs); //当前流写入二进制 byte[] postArray = br.ReadBytes((int)fs.Length); //打开流以二进制方式写入指定资源 Stream postStream = myWebClient.OpenWrite(uriString,"PUT"); try { if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); postStream.Close(); fs.Dispose(); MessageBox.Show("上传成功"); } else { postStream.Close(); fs.Dispose(); MessageBox.Show("上传失败"); } } catch (Exception ex) { postStream.Close(); fs.Dispose(); MessageBox.Show("上传文件异常" + ex.Message); throw ex; } finally { postStream.Close(); fs.Dispose(); } } /// /// 下载服务器文件至客户端 /// /// 被下载的文件地址,绝对路径 /// 另存放的目录 public void DownLoad(string URL,string Dir) { WebClient client = new WebClient(); string fileName = URL.Substring(URL.LastIndexOf("//")+1);//被下载的文件名 string Path = Dir + fileName;//另存为的绝对路径+文件名 try { WebRequest myRe = WebRequest.Create(URL); } catch (Exception ex) { MessageBox.Show("下载文件异常"+ex.Message); } try { client.DownloadFile(URL, fileName); FileStream fs = new FileStream(fileName,FileMode.Open,FileAccess.Read); BinaryReader br = new BinaryReader(fs); byte[] mybyte = br.ReadBytes((int)fs.Length); FileStream fstm = new FileStream(Path,FileMode.Create,FileAccess.Write); fstm.Write(mybyte,0,(int)fs.Length); fstm.Close(); MessageBox.Show("下载文件成功!"); } catch (Exception ex) { MessageBox.Show("下载文件异常"+ex.Message); } } } }

你可能感兴趣的:(C#,winform,c#,string,exception,服务器,url)