2010-05-13 275 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; 

你没有显示的响应,你可以得到它,关闭它,我显示它仅供参考。