简体   繁体   中英

File upload on FTP server not working

I am trying to upload a file to my ftp server. 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. You have only prepared the request to be sent in your code.

To quote MSDN,

GetResponse causes a control connection to be established, and might also create a data connection. GetResponse blocks until the response is received. To prevent this, you can perform this operation asynchronously by calling the BeginGetResponse and EndGetResponse methods in place of GetResponse.

So, After writing the file contents, call

ftp.GetResponse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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