7

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 would use:

var request = (FtpWebRequest)WebRequest.Create("ftp://www.mysite.com/test.jpg");
request.Credentials = new NetworkCredential(user, pass);
request.Method = WebRequestMethods.Ftp.Rename;
request.RenameTo = "testrename.jpg"
request.GetResponse().Close();

FtpWebResponse resp = (FtpWebResponse)request.GetResponse();

However, there is no Method for copying files. How would you do copy a file?

msbg
  • 4,852
  • 11
  • 44
  • 73
  • Do you have other access to the server? FTP is, by virtue of its name, more for transferring files than for remote management of those files. – Joe Apr 14 '13 at 23:07
  • No, I'm actually making an FTP web app for anyone to use. – msbg Apr 14 '13 at 23:10
  • 1
    Then you should read up on the RFC and see what capabilities are actually possible with the protocol. – Joe Apr 14 '13 at 23:13
  • Probably should do that. I'll just download and upload the file with a new name for now. – msbg Apr 14 '13 at 23:30

4 Answers4

10

Try this:

static void Main(string[] args)
{
    CopyFile("countrylist.csv", "MySample.csv", "username", "password#");
}

public static bool CopyFile(string fileName, string FileToCopy, string userName, string password)
{
    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.mysite.net/" + fileName);
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        request.Credentials = new NetworkCredential(userName, password);
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();
        Upload("ftp://ftp.mysite.net/" + FileToCopy, ToByteArray(responseStream), userName, password);
        responseStream.Close();
        return true;
    }
    catch
    {
        return false;
    }
}

public static Byte[] ToByteArray(Stream stream)
{
    MemoryStream ms = new MemoryStream();
    byte[] chunk = new byte[4096];
    int bytesRead;
    while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
    {
        ms.Write(chunk, 0, bytesRead);
    }

    return ms.ToArray();
}

public static bool Upload(string FileName, byte[] Image, string FtpUsername, string FtpPassword)
{
    try
    {
        System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(FileName);
        clsRequest.Credentials = new System.Net.NetworkCredential(FtpUsername, FtpPassword);
        clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
        System.IO.Stream clsStream = clsRequest.GetRequestStream();
        clsStream.Write(Image, 0, Image.Length);

        clsStream.Close();
        clsStream.Dispose();
        return true;
    }
    catch
    {
        return false;
    }
}

This downloads the file to a stream, and then uploads it.

eandersson
  • 25,781
  • 8
  • 89
  • 110
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
  • Can I copy files or upload from ftp server to http server? let's say I want to transfer ftp://ftpabcdef.com/abcdef.xml to http://xyzed.com/abcdef.xml. Is it possible with this code? or anything i need to write for this – ratna Mar 29 '18 at 08:06
  • @ratna You will not be able to accomplish that with this code. It seems like you will have better luck asking a new question. You would need to get the file through FTP, download it somewhere (memory?), and then do a HTTP POST to upload the file to your HTTP server. – Hanlet Escaño Mar 29 '18 at 15:20
  • thanks @HanletEscaño for reply . I asked this kind of qs but it got negative point and finally closed . So I have to download the file into my local machine and then I can upload it to http server? ..but can you tell me is it possible to transfer file from ftp to http using powershell or C# or any other language ? it's a silly qs I know but I'm asking cause I don't have any idea about this . – ratna Mar 30 '18 at 08:12
2

FtpWebRequest is a lightweight class. Microsoft felt it should be used by simple client to download and delete the files once the client is finish.

Black Frog
  • 11,595
  • 1
  • 35
  • 66
1

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)
        {

        }
    }
msbg
  • 4,852
  • 11
  • 44
  • 73
1

In our project we did someting like this

// pass parameters according to your need, 
// the below code is done in a hard coded manner for clarity
public void Copy()  
{
    // from where you want to copy
    var downloadRequest = (FtpWebRequest)WebRequest.Create("ftp://www.mysite.com/test.jpg");
    downloadRequest.Credentials = new NetworkCredential("userName", "passWord");
    downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;

    var ftpWebResponse = (FtpWebResponse)downloadRequest.GetResponse();
    var downloadResponse = ftpWebResponse.GetResponseStream();

    int buffLength = 2048;
    byte[] byteBuffer = new byte[buffLength];

    // bytes read from download stream. 
    // from documentation: When overridden in a derived class, reads a sequence of bytes from the  
    // current stream and advances the position within the stream by the number of bytes read.
    int bytesRead = downloadResponse.Read(byteBuffer, 0, buffLength);

    // the place where you want the file to go
    var uploadRequest = (FtpWebRequest)WebRequest.Create("ftp://www.mysite.com/testCopy.jpg");
    uploadRequest.Credentials = new NetworkCredential("userName", "passWord");
    uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;

    var uploadStream = uploadRequest.GetRequestStream();

    if (bytesRead > 0)
    {
        while (bytesRead > 0)
        {
            uploadStream.Write(byteBuffer, 0, bytesRead);
            bytesRead = downloadResponse.Read(byteBuffer, 0, buffLength);
        }
    }

    uploadStream.Close();
    uploadStream.Dispose();

    downloadResponse.Close();
    ftpWebResponse.Close();
    ((IDisposable)ftpWebResponse).Dispose();
}
Yousuf Azad
  • 414
  • 1
  • 7
  • 17