c# – 如何在FTP服务器上复制文件?

前端之家收集整理的这篇文章主要介绍了c# – 如何在FTP服务器上复制文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在FTP服务器上复制文件?我的目标是将ftp://www.mysite.com/test.jpg复制到ftp://www.mysite.com/testcopy.jpg.要重命名文件,我会使用:
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();

但是,没有复制文件方法.你会如何复制文件

解决方法

试试这个:
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,chunk.Length)) > 0)
    {
        ms.Write(chunk,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,Image.Length);

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

这会将文件下载到流中,然后上载它.

原文链接:https://www.f2er.com/csharp/95889.html

猜你在找的C#相关文章