如何在 FTP 服务器上复制文件? [英] How to copy a file on an FTP server?

查看:43
本文介绍了如何在 FTP 服务器上复制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 FTP 服务器上复制文件?我的目标是将 ftp://www.mysite.com/test.jpg 复制到 ftp://www.mysite.com/testcopy.jpg.要重命名文件,我会使用:

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?

推荐答案

试试这个:

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.

这篇关于如何在 FTP 服务器上复制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆