如何从一个FTP下载文件,然后上传文件到不同的FTP?

时间:2015-07-14 20:05:25

标签: c# download upload ftp ftpwebrequest

我正在尝试从一台FTP服务器下载文件,然后将其上传到其他FTP。到目前为止,我只想知道如何通过FTP上传本地文件和下载XML。

以下是将本地文件上传到FTP的方法:

    private void UploadLocalFile(string sourceFileLocation, string targetFileName)
    {
        try
        {
            string ftpServerIP = "ftp://testing.com/ContentManagementSystem/"+ Company +"/Prod";
            string ftpUserID = Username;
            string ftpPassword = Password;
            string filename = "ftp://" + ftpServerIP + "/" + targetFileName;
            FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
            ftpReq.UseBinary = true;
            ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
            ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            ftpReq.Proxy = null;

            byte[] b = File.ReadAllBytes(sourceFileLocation);

            ftpReq.ContentLength = b.Length;
            using (Stream s = ftpReq.GetRequestStream())
            {
                s.Write(b, 0, b.Length);
            }
        }
        catch (WebException ex)
        {
            String status = ((FtpWebResponse)ex.Response).StatusDescription;
            Console.WriteLine(status);
        }
    }

这是我从FTP下载XML的方法:

    private static XmlDocument DownloadFtpXml(string uri, int retryLimit)
    {
        var returnDocument = new XmlDocument();
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(Username, Password);
            request.UsePassive = true;
            request.Proxy = new WebProxy();

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

            using (Stream responseStream = response.GetResponseStream())
            {
                returnDocument.Load(responseStream);
            }
        }
        catch (WebException ex)
        {
            if (ex.Response != null)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                }
            }
        }
        return returnDocument;
    }

我不确定该怎么做,但我试图创建一种方法,从一个FTP下载内容(内容将是一个视频或图像),然后转身上传我和我#39;刚刚下载(我已经在内存中保存)到另一台FTP。

请帮忙!

1 个答案:

答案 0 :(得分:1)

你太近了!使用流将下载转换为字节数组以进行上载。

我最近做了一个程序就是这样做的!只要目标目录中没有同名文件,这将把所有文件从一个FTP目录复制到另一个FTP目录。如果你只想复制一个文件,只需使用copyFile,toByteArray和上传函数,就很容易改变:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace Copy_From_FTP
{
    class Program
    {

        public static void Main(string[] args)
        {
            List<FileName> sourceFileList = new List<FileName>();
            List<FileName> targetFileList = new List<FileName>();

            //string targetURI = ftp://www.target.com
            //string targetUser = userName
            //string targetPass = passWord
            //string sourceURI = ftp://www.source.com
            //string sourceUser = userName
            //string sourcePass = passWord

            getFileLists(sourceURI, sourceUser, sourcePass, sourceFileList, targetURI, targetUser, targetPass, targetFileList);

            Console.WriteLine(sourceFileList.Count + " files found!");

            CheckLists(sourceFileList, targetFileList);
            targetFileList.Sort();

            Console.WriteLine(sourceFileList.Count + " unique files on sourceURI"+Environment.NewLine+"Attempting to move them.");

            foreach(var file in sourceFileList)
            {
                try
                {
                    CopyFile(file.fName, sourceURI, sourceUser, sourcePass, targetURI, targetUser, targetPass);
                }
                catch
                {
                    Console.WriteLine("There was move error with : "+file.fName);
                }                    
            }            
        }

        public class FileName : IComparable<FileName>
        {
            public string fName { get; set; }
            public int CompareTo(FileName other)
            {
                return fName.CompareTo(other.fName);
            }
        }

        public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)
        {
            for (int i = 0; i < sourceFileList.Count;i++ )
            {
                if (targetFileList.BinarySearch(sourceFileList[i]) > 0)
                {
                    sourceFileList.RemoveAt(i);
                    i--;
                }
            }
        }

        public static void getFileLists(string sourceURI, string sourceUser, string sourcePass, List<FileName> sourceFileList,string targetURI, string targetUser, string targetPass, List<FileName> targetFileList)
        {
            string line = "";
            /////////Source FileList
            FtpWebRequest sourceRequest;
            sourceRequest = (FtpWebRequest)WebRequest.Create(sourceURI);
            sourceRequest.Credentials = new NetworkCredential(sourceUser, sourcePass);
            sourceRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            sourceRequest.UseBinary = true;
            sourceRequest.KeepAlive = false;
            sourceRequest.Timeout = -1;
            sourceRequest.UsePassive = true;
            FtpWebResponse sourceRespone = (FtpWebResponse)sourceRequest.GetResponse();
            //Creates a list(fileList) of the file names
            using (Stream responseStream = sourceRespone.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    line = reader.ReadLine();
                    while (line != null)
                    {
                        var fileName = new FileName
                        {
                            fName = line
                        };
                        sourceFileList.Add(fileName);
                        line = reader.ReadLine();
                    }
                }
            }
            /////////////Target FileList
            FtpWebRequest targetRequest;
            targetRequest = (FtpWebRequest)WebRequest.Create(targetURI);
            targetRequest.Credentials = new NetworkCredential(targetUser, targetPass);
            targetRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            targetRequest.UseBinary = true;
            targetRequest.KeepAlive = false;
            targetRequest.Timeout = -1;
            targetRequest.UsePassive = true;
            FtpWebResponse targetResponse = (FtpWebResponse)targetRequest.GetResponse();
            //Creates a list(fileList) of the file names
            using (Stream responseStream = targetResponse.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    line = reader.ReadLine();
                    while (line != null)
                    {
                        var fileName = new FileName
                        {
                            fName = line
                        };
                        targetFileList.Add(fileName);
                        line = reader.ReadLine();
                    }
                }
            }
        }

        public static void CopyFile(string fileName, string sourceURI, string sourceUser, string sourcePass,string targetURI, string targetUser, string targetPass )
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceURI + fileName);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(sourceUser, sourcePass);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                Upload(fileName, ToByteArray(responseStream),targetURI,targetUser, targetPass);
                responseStream.Close();
            }
            catch
            {
                Console.WriteLine("There was an error with :" + fileName);
            }
        }

        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 targetURI,string targetUser, string targetPass)
        {
            try
            {
                FtpWebRequest clsRequest = (FtpWebRequest)WebRequest.Create(targetURI+FileName);
                clsRequest.Credentials = new NetworkCredential(targetUser, targetPass);
                clsRequest.Method = WebRequestMethods.Ftp.UploadFile;
                Stream clsStream = clsRequest.GetRequestStream();
                clsStream.Write(Image, 0, Image.Length);
                clsStream.Close();
                clsStream.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

如果您使用具有特殊编码的内容(如文本文档),则可能会遇到问题。这可以通过上传功能的使用方式来改变。如果您正在处理文本文件,请使用:

 System.Text.Encoding.UTF8.GetBytes(responseStream)

而不是

ToByteArray(responseStream)

在执行上传之前,您可以对文件进行简单的扩展检查。