我有一個上傳文件到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握手從來沒有發生過第二次。
etarvt,在哪一行發生超時,我猜「Stream ftpStream = reqFTP.GetRequestStream();」 ?謝謝。 – 2011-01-16 06:09:15