C# FtpWebRequest 创建损坏的文件

C# FtpWebRequest creates corrupted files

我正在使用 .NET 3.5,我需要通过 FTP 传输一些文件。 我不想使用文件,因为我使用 MemoryStreambytes arrays.

来管理所有文件

阅读这些文章(article and article),我做了我的客户

public void Upload(byte[] fileBytes, string remoteFile)
{
    try
    {
        string uri = string.Format("{0}:{1}/{2}", Hostname, Port, remoteFile);
        FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(uri);
        ftp.Credentials = new NetworkCredential(Username.Normalize(), Password.Normalize());

        ftp.UseBinary = true;
        ftp.UsePassive = true;
        ftp.Method = WebRequestMethods.Ftp.UploadFile;

        using (Stream localFileStream = new MemoryStream(fileBytes))
        {
            using (Stream ftpStream = ftp.GetRequestStream())
            {
                int bufferSize = (int)Math.Min(localFileStream.Length, 2048);
                byte[] buffer = new byte[bufferSize];
                int bytesSent = -1;

                while (bytesSent != 0)
                {
                    bytesSent = localFileStream.Read(buffer, 0, bufferSize);
                    ftpStream.Write(buffer, 0, bufferSize);
                }
            }
        }
    }
    catch (Exception ex)
    {
        LogHelper.WriteLog(logs, "Errore Upload", ex);
        throw;
    }
}

FTP客户端正确连接、写入和关闭,没有任何错误。但是写入的文件已损坏,例如 PDF 无法打开 DOC/DOCX Word 显示有关文件损坏的消息并尝试恢复它们。

如果我将传递给上传方法的相同字节写入文件,我会得到一个正确的文件。所以问题一定出在 FTP transfer.

byte[] fileBytes = memoryStream.ToArray();
File.WriteAllBytes(@"C:\test.pdf", fileBytes); // --> File OK!
ftpClient.Upload(fileBytes, remoteFile); // --> File CORRUPTED on FTP folder!

您需要在 Write 调用中使用 bytesSent

bytesSent = localFileStream.Read(buffer, 0, bufferSize);
ftpStream.Write(buffer, 0, bytesSent);

不然你最后一轮写的字节太多了