简体   繁体   English

FTP服务器上的文件上传不起作用

[英]File upload on FTP server not working

I am trying to upload a file to my ftp server. 我正在尝试将文件上传到我的ftp服务器。 Unfortunately, the upload method seems to work but does not upload my selected file. 不幸的是,上载方法似乎可行,但无法上载我选择的文件。 Please, see my code below: 请在下面查看我的代码:

public void UploadFileToFTP(string source)
    {
        try
        {
            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://xxx.bplaced.net/Test");
            ftp.Credentials = new NetworkCredential("BN", "PW");

            ftp.KeepAlive = true;
            ftp.UseBinary = true;
            ftp.Method = WebRequestMethods.Ftp.UploadFile;

            FileStream fs = File.OpenRead(source);
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            fs.Close();

            Stream ftpstream = ftp.GetRequestStream();
            ftpstream.Write(buffer, 0, buffer.Length);
            ftpstream.Close();

            MessageBox.Show("Upload successful!");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

public void button_Upload_Click(object sender, RoutedEventArgs e)
    {
        string sourcefilepath = @"C:\Users\MyPC\Desktop\Test\Texts\New.html";
        UploadFileToFTP(sourcefilepath);
    }

Please see this screenshot: What is meant by "Is a directory"? 请看下面的截图:“是目录”是什么意思?

屏幕截图

Error is clear: Problem fixed. 错误明确: 问题已解决。

You should call the GetResponse() method to actually send the ftp request. 您应该调用GetResponse()方法来实际发送ftp请求。 You have only prepared the request to be sent in your code. 您仅准备了要在代码中发送的请求。

To quote MSDN, 引用MSDN,

GetResponse causes a control connection to be established, and might also create a data connection. GetResponse导致建立控件连接,并且还可能创建数据连接。 GetResponse blocks until the response is received. GetResponse阻塞,直到收到响应为止。 To prevent this, you can perform this operation asynchronously by calling the BeginGetResponse and EndGetResponse methods in place of GetResponse. 为避免这种情况,您可以通过调用BeginGetResponse和EndGetResponse方法代替GetResponse来异步执行此操作。

So, After writing the file contents, call 所以,写完文件内容后,调用

ftp.GetResponse()

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

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