我正在使用。net 3.5,我需要通过FTP传输一些文件。我不想使用文件,因为我使用MemoryStream
和bytes arrays
来管理所有文件。
阅读这些文章(一篇又一篇),我使我的客户。
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显示有关文件损坏的消息并试图恢复它们。
如果我将传递给Upload方法的相同字节写入文件,我将得到正确的文件。所以问题一定出在FTP传输上。
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);