简体   繁体   English

C#上传文件到FTP服务器

[英]c# Uploading files to ftp server

I have a problem with uploading files to ftp server. 我将文件上传到ftp服务器时遇到问题。 I have a few buttons. 我有几个按钮。 Every button uploads different files to the ftp. 每个按钮会将不同的文件上传到ftp。 The first time when a button is clicked the file is uploaded successfully, but the second and later tries fail. 第一次单击按钮时,文件已成功上传,但是第二次及以后的尝试均失败。 It gives me "The operation has timed out". 它给我“操作已超时”。 When I close the site and then open it again I can upload again only one file. 关闭网站然后再次打开时,我只能再次上传一个文件。 I am sure that I can override files on the ftp. 我确定我可以覆盖ftp上的文件。 Here's the code: 这是代码:

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;    
    }

Does anyone have idea what may cause this strange behaviour? 有谁知道导致这种奇怪行为的原因? I think I'm closing all streams accurately. 我想我正在准确地关闭所有流。 Could this be related with the ftp server settings? 这与ftp服务器设置有关吗? The admin said that the ftp handshake never happened second time. 管理员说,ftp握手从未第二次发生。

start with wrapping your Stream creation in a using clause. 首先将您的Stream创建包装在using子句中。

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

            // fill the stream

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

        }

This will make sure that the stream is closed and that any unmanaged resources are disposed, whether an error occurs or not 这将确保关闭流,并且无论是否发生错误,都将处置所有非托管资源。

I used your code, had the same problem, and fixed it. 我使用了您的代码,遇到了同样的问题,并将其修复。

After you close the stream, you have to read reqFTP response by calling GetResponse() then close the response . 关闭流后,您必须通过调用GetResponse() 阅读reqFTP response然后关闭响应 Here is the code that fixes the problem: 这是解决问题的代码:

// 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;

You don't have to display the response, you can just get it and close it, I am displaying it just for reference. 您不必显示响应,您只需获取并关闭它,我将其显示为参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM