2010-05-13 272 views
1

我有一個上傳文件到FTP服務器的問題。我有幾個按鈕。每個按鈕都會將不同的文件上傳到ftp。第一次單擊按鈕時,文件成功上傳,但第二次和以後嘗試失敗。它給了我「手術已經超時」。當我關閉網站並再次打開時,我只能再次上傳一個文件。我確信我可以覆蓋ftp上的文件。這裏是代碼:c#上傳文件到FTP服務器

protected void btn_export_OnClick(object sender, EventArgs e) 
{ 
    Stream stream = new MemoryStream(); 

    stream.Position = 0; 

    // fill the stream 

    bool res = this.UploadFile(stream, "test.csv", "dir"); 

    stream.Close(); 
} 

private bool UploadFile(Stream stream, string filename, string ftp_dir) 
{ 
     stream.Seek(0, SeekOrigin.Begin); 

     string uri = String.Format("ftp://{0}/{1}/{2}", "host", ftp_dir, filename); 

     try 
     { 
      FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 

      reqFTP.Credentials = new NetworkCredential("user", "pass"); 
      reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 
      reqFTP.KeepAlive = false; 
      reqFTP.UseBinary = true; 
      reqFTP.UsePassive = true; 
      reqFTP.ContentLength = stream.Length; 
      reqFTP.EnableSsl = true; // it's FTPES type of ftp 

      int buffLen = 2048; 
      byte[] buff = new byte[buffLen]; 
      int contentLen; 

      try 
      { 
       Stream ftpStream = reqFTP.GetRequestStream(); 
       contentLen = stream.Read(buff, 0, buffLen); 
       while (contentLen != 0) 
       { 
        ftpStream.Write(buff, 0, contentLen); 
        contentLen = stream.Read(buff, 0, buffLen); 
       } 
       ftpStream.Flush(); 
       ftpStream.Close(); 
      } 
      catch (Exception exc) 
      { 
       this.lbl_error.Text = "Error:<br />" + exc.Message; 
       this.lbl_error.Visible = true; 

       return false; 
      } 
     } 
     catch (Exception exc) 
     { 
      this.lbl_error.Text = "Error:<br />" + exc.Message; 
      this.lbl_error.Visible = true; 

      return false; 
     } 

     return true;  
    } 

有沒有人有想法可能會導致這種奇怪的行爲?我想我正在關閉所有的流。這可能與FTP服務器設置有關嗎?管理員說,ftp握手從來沒有發生過第二次。

+0

etarvt,在哪一行發生超時,我猜「Stream ftpStream = reqFTP.GetRequestStream();」 ?謝謝。 – 2011-01-16 06:09:15

回答

2

首先在使用子句中包裝流創建。

 using(Stream stream = new MemoryStream()) 
     { 
      stream.Position = 0; 

      // fill the stream 

      bool res = this.UploadFile(stream, "test.csv", "dir"); 

     } 

這將確保流被關閉,任何非託管資源配置,是否發生錯誤或不

+0

好的,謝謝你的回覆,我會試試看。 – etarvt 2010-05-13 16:03:09

+0

它可能不是你的錯誤的來源,但它是好的做法 – 2010-05-13 16:18:26

+0

我試了一下。但問題依然存在,或許它不是來源。我嘗試了KeepAlive = true,但它也沒有改變。 – etarvt 2010-05-13 17:16:42

1

我用你的代碼,有同樣的問題,並固定它。

在您關閉流,你必須通過調用GetResponse()然後關閉響應reqFTP response。下面是解決該問題的代碼:

// Original code 
ftpStream.Flush(); 
ftpStream.Close(); 

// Here is the missing part that you have to add to fix the problem 
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 
this.lbl_error.Text = "Response:<br />" + response.StatusDescription; 
response.Close(); 
reqFTP = null; 
this.lbl_error.Visible = true; 

你沒有顯示的響應,你可以得到它,關閉它,我顯示它僅供參考。