上传到FTP并使用FtpWebRequest下载后,存档或映像已损坏

时间:2017-10-23 07:47:32

标签: c# .net ftp zip ftpwebrequest

我有两种方法:

  1. 将文件上传到FTP服务器
  2. 从服务器下载文件。
  3. 一切都与文本或xml文件完美配合。但是,当我尝试上传然后下载档案或图像时,我得到“Windows无法打开文件夹。压缩的zip文件无效”,档案错误,图像几乎相同。可能是什么问题?

    以下是我的方法列表:

    上载:

    private string Upload(string Login, string Password, string FilePath, string FileName, string uuid, string FTPDir)
    {
        string CreateDirectory = CreateFTPDirectory(Login, Password, uuid, FTPDir);
    
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(@"ftp://" + FTPDir + uuid + "/" + FileName);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.UseBinary = true;
    
        StreamReader sourceStream = new StreamReader(FilePath + FileName);
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;
    
        using (Stream S = request.GetRequestStream())
        {
            S.Write(fileContents, 0, fileContents.Length);
        }
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        response.Close();
    
        return response.StatusDescription;
    }
    

    下载:

    private string Download(string Login, string Password, string FileName, string uuid, string FTPDir, string Destination)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + FTPDir + uuid + "/" + FileName);
        request.UseBinary = true;
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.Credentials = new NetworkCredential(Login, Password);
        byte[] buffer = new byte[1024];
    
        using (var response = (FtpWebResponse)request.GetResponse())
        {
    
            using (var stream = response.GetResponseStream())
            {
                using (var fs = new FileStream(Destination, FileMode.OpenOrCreate))
                {
                    int readCount = stream.Read(buffer, 0, 1024);
    
                    while (readCount > 0)
                    {
                        fs.Write(buffer, 0, readCount);
                        readCount = stream.Read(buffer, 0, 1024);                            
                    }
                }
                return response.StatusDescription;
            }
        }
    }
    

1 个答案:

答案 0 :(得分:4)

您正在上传二进制文件(位图图像​​),就像它是UTF-8编码的文本文件一样:

byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

这自然会破坏文件。

您必须完全按原样传输二进制文件。

此外,对于潜在的大型图像文件,您的技术效率非常低。您将整个文件保留在内存中至少两次。

您需要的代码实际上比您的代码简单得多:

using (Stream fileStream = File.OpenRead(FilePath + FileName)
using (Stream ftpStream = request.GetRequestStream())
{
    fileStream.CopyTo(ftpStream);
}

您的下载代码没问题,但同样可以简化为:

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(Destination))
{
    ftpStream.CopyTo(fileStream);
}

有关完整代码,请参阅Upload and download a binary file to/from FTP server in C#/.NET