【问题标题】:c# Uploading files to ftp serverc# 上传文件到ftp服务器
【发布时间】:2025-09-07 00:35:02
【问题描述】:

我在将文件上传到 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 握手从未发生过第二次。

【问题讨论】:

  • etarvt,超时发生在哪一行,我猜是“Stream ftpStream = reqFTP.GetRequestStream();” ?谢谢。

标签: c# upload ftp


【解决方案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;

你不必显示响应,你可以得到它并关闭它,我显示它只是为了参考。

【讨论】:

    【解决方案2】:

    首先将您的 Stream 创建包装在 using 子句中。

            using(Stream stream = new MemoryStream())
            {
                stream.Position = 0;
    
                // fill the stream
    
                bool res = this.UploadFile(stream, "test.csv", "dir");
    
            }
    

    这将确保流被关闭并且所有非托管资源都被释放,无论是否发生错误

    【讨论】:

    • 这可能不是您的错误的根源,但这是一种很好的做法
    • 我试过了。但是问题依然存在,真的可能不是源头。我尝试使用 KeepAlive = true,但它也没有改变任何东西。