C# WinForm 檔案上傳下載

來源:互聯網
上載者:User

標籤:winform   style   blog   color   os   使用   檔案   for   ar   

/// <summary>  /// WebClient上傳檔案至伺服器  /// </summary>  /// <param name="fileNamePath">檔案名稱,全路徑格式</param>  /// <param name="uriString">伺服器檔案夾路徑</param>  private void UpLoadFile(string fileNamePath,string uriString)  {   string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);   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執行個體   WebClient myWebClient = new WebClient();   myWebClient.Credentials = CredentialCache.DefaultCredentials;   // 要上傳的檔案   FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);   //FileStream fs = OpenFile();   BinaryReader r = new BinaryReader(fs);   try   {    //使用UploadFile方法可以用下面的格式    //myWebClient.UploadFile(uriString,"PUT",fileNamePath);    byte[] postArray = r.ReadBytes((int)fs.Length);    Stream postStream = myWebClient.OpenWrite(uriString,"PUT");    if(postStream.CanWrite)    {     postStream.Write(postArray,0,postArray.Length);    }    else    {     AppHelper.MessageService.ShowError("檔案目前不可寫!");    }    postStream.Close();   }   catch   {    AppHelper.MessageService.ShowError("檔案上傳失敗,請稍候重試~");   }  }  /// <summary>  /// 下載伺服器檔案至用戶端  /// </summary>  /// <param name="URL">被下載的檔案地址,絕對路徑</param>  /// <param name="Dir">另存放的目錄</param>  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   {    //MessageBox.Show(exp.Message,"Error");    }      try   {    client.DownloadFile(URL,fileName);    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);    BinaryReader r = new BinaryReader(fs);    byte[] mbyte = r.ReadBytes((int)fs.Length);    FileStream fstr = new FileStream(Path,FileMode.OpenOrCreate,FileAccess.Write);     fstr.Write(mbyte,0,(int)fs.Length);    fstr.Close();    }    catch   {    //MessageBox.Show(exp.Message,"Error");   }   }  

 

C# WinForm 檔案上傳下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.