0

大家好,

是否可以使用 C# 中的 FTP 功能将文件从一个文件夹 FTP 传输到另一个文件夹。

这两个文件夹都在同一个 Unix 服务器上。

当我尝试这样做时,我得到错误'无法将'System.Net.FileWebRequest'类型的对象转换为'System.Net.FtpWebRequest''

谢谢

4

1 回答 1

0

这会下载文件,然后将其上传到特定目录

    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;
        }
    }
于 2013-06-11T13:29:12.720 回答