How to copy a file on an FTP server?

前端 未结 4 937
野的像风
野的像风 2020-12-31 23:27

How do you copy a file on an FTP server? My goal is to copy ftp://www.mysite.com/test.jpg to ftp://www.mysite.com/testcopy.jpg. To rename a file, I

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 00:23

    I guess you can't really do this with FTP. What you can do is download the file you want to copy and then upload it with a new name. For example:

            try
            {
                WebClient request = new WebClient();
                request.Credentials = new NetworkCredential(user, pass);
                byte[] data = request.DownloadData(host);
                MemoryStream file = new MemoryStream(data);
                Upload(data);
            }
            catch (Exception ex)
            {
    
            }
    
        ...
    
        private void Upload(byte[] buffer)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(newname);
    
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(user, pass);
    
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
    
                var resp = (FtpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
    
            }
        }
    

提交回复
热议问题