【问题标题】:How to Download file from one FTP and then Upload file to different FTP?如何从一个 FTP 下载文件,然后将文件上传到不同的 FTP?
【发布时间】:2015-10-03 15:48:59
【问题描述】:

我正在尝试从一个 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 下载某些内容(内容是视频或图像),然后转身上传我刚刚下载的内容(我会记住的)到另一个 FTP。

请帮忙!

【问题讨论】:

  • 您可以改用 SFTP 吗?是否允许使用第三方工具? stackoverflow.com/questions/6415562/…
  • 将 Xml 文档保存在临时本地文件中,然后上传。看起来你有所有的代码,只需要添加一个额外的步骤。虽然您说内容将是视频或图像,但为什么要将其保存在 Xml 文档中(如果您尝试 .Load 不是 Xml 的内容会引发异常)?
  • 您可以直接从输入流(从下载获得)复制到输出流(用于在上传过程中写入),而不是临时文件。
  • 好极了。我会尝试以上这些选项的一些组合并报告回来。我们还没有设置使用 SFTP,否则我会走那条路。第三方工具是可以接受的,但我会尝试临时本地路线,看看会带我去哪里!

标签: c# download upload ftp ftpwebrequest


【解决方案1】:

你离得太近了!使用流将您的下载转换为字节数组以供上传。

我最近做了一个程序来做到这一点!只要目标目录中没有同名文件,这当前会将所有文件从一个 FTP 目录复制到另一个目录。如果您只想复制一个文件,则很容易更改,只需使用copyFile,toByteArray和upload函数即可:

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)

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

【讨论】:

    猜你喜欢
    • 2012-10-18
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2014-08-05
    • 2011-06-20
    • 1970-01-01
    相关资源
    最近更新 更多