簡體   English   中英

C#上傳文件到FTP服務器

[英]c# Uploading files to ftp server

我將文件上傳到ftp服務器時遇到問題。 我有幾個按鈕。 每個按鈕會將不同的文件上傳到ftp。 第一次單擊按鈕時,文件已成功上傳,但是第二次及以后的嘗試均失敗。 它給我“操作已超時”。 關閉網站然后再次打開時,我只能再次上傳一個文件。 我確定我可以覆蓋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握手從未第二次發生。

首先將您的Stream創建包裝在using子句中。

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

            // fill the stream

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

        }

這將確保關閉流,並且無論是否發生錯誤,都將處置所有非托管資源。

我使用了您的代碼,遇到了同樣的問題,並將其修復。

關閉流后,您必須通過調用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;

您不必顯示響應,您只需獲取並關閉它,我將其顯示為參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM