asp.net c#利用FtpWebRequest上傳下載檔案執行個體

來源:互聯網
上載者:User

asp教程.net c#利用FtpWebRequest上傳下載檔案執行個體
根據uri建立FtpWebRequest對象
  FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(strUri));
  // ftp使用者名稱和密碼
  ftpReq.Credentials = new NetworkCredential("使用者名稱", "密碼");
  // 指定執行什麼命令
  ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
  //成功執行一個命令後串連被關閉
  ftpReq.KeepAlive = false;
  //指定資料轉送類型為二進位
  ftpReq.UseBinary = true;
  //上傳檔案時通知伺服器檔案的大小  
  ftpReq.ContentLength = fi.Length;
  // 緩衝大小設定為2kb  
  int buffLength = 2048;  
  byte[] buff = new byte[buffLength];

  int contentLen;
   

  try
  {
  //開啟一個檔案流去讀上傳的檔案
  FileStream fs = fi.OpenRead();
  //把上傳的檔案寫入流
  Stream strm = ftpReq.GetRequestStream();

  //每次讀檔案流的2kb  
 

contentLen = fs.Read(buff, 0, buffLength);
   
  while (contentLen != 0) // 流內容沒有結束
  {
  // 把內容從file stream 寫入 upload stream 
  strm.Write(buff, 0, contentLen);  
  contentLen = fs.Read(buff, 0, buffLength);  
  }
  strm.Close();
  fs.Close();
  }
  catch (Exception e)
  {
   
  }


  '方法二
 

  FileInfo file = new FileInfo("G:/www.111cn.net/室內設計01.jpg");
                if (file.Exists)
                {
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(file.Name));
                    Response.AddHeader("Content-Length", file.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.Filter.Close();
                    Response.WriteFile(file.FullName);
                    Response.End();
                }


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.