C# C FtpWebRequest创建损坏的文件
我正在使用.NET3.5,我需要通过FTP传输一些文件。 我不想使用文件,因为我使用MemoryStream和字节数组来管理所有文件 读了这些文章,我把我的客户C# C FtpWebRequest创建损坏的文件,c#,.net,ftp,stream,corruption,C#,.net,Ftp,Stream,Corruption,我正在使用.NET3.5,我需要通过FTP传输一些文件。 我不想使用文件,因为我使用MemoryStream和字节数组来管理所有文件 读了这些文章,我把我的客户 public void Upload(byte[] fileBytes, string remoteFile) { try { string uri = string.Format("{0}:{1}/{2}", Hostname, Port, remoteFile); FtpWebRequ
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!
您需要在写调用中使用bytesSent:
否则,在上一轮中写入的字节太多。到达另一端的文件的长度是否完全相同?它有没有可能提前一点截断?
bytesSent = localFileStream.Read(buffer, 0, bufferSize);
ftpStream.Write(buffer, 0, bytesSent);