2014-12-03 173 views
1

我正尝试在上传到FTP服务器之前使用GZipStream压缩文档。如果在上传之前将压缩文件流保存到磁盘,则本地文件系统上的副本是正确的。但是,当我尝试在FTP服务器上解压缩文件时,出现7zip中的'File is broken'错误。由此产生的解压缩文件是正确的,直到字符序列重复时的最后几个字符。我尝试了许多不同的配置无济于事。FTP + GZipStream =解压缩文件时'文件已损坏'

public static void FTPPut_Compressed(string fileContents, string ftpPutPath) 
    { 
     using (var inStream = new System.IO.MemoryStream(System.Text.Encoding.Default.GetBytes(fileContents))) 
     { 
     inStream.Seek(0, SeekOrigin.Begin); 
     using (var outStream = new System.IO.MemoryStream()) 
     { 
      using (var zipStream = new GZipStream(outStream, CompressionMode.Compress)) 
      { 
       inStream.CopyTo(zipStream); 
       outStream.Seek(0, SeekOrigin.Begin); 
       FTPPut(ftpPutPath, outStream.ToArray()); 
      } 
     } 
     } 
    } 

    private static void FTPPut(string ftpPutPath, byte[] fileContents) 
    { 
     FtpWebRequest request; 

     request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}", Constants.FTPServerAddress, ftpPutPath))) as FtpWebRequest; 
     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.UseBinary = true; 
     request.UsePassive = true; 
     request.KeepAlive = true; 
     request.Credentials = new NetworkCredential(Constants.FTPUserName, Constants.FTPPassword); 
     request.ContentLength = fileContents.Length; 

     using (var requestStream = request.GetRequestStream()) 
     { 
     requestStream.Write(fileContents, 0, fileContents.Length); 
     requestStream.Close(); 
     requestStream.Flush(); 
     } 
    } 

防爆损坏输出:

<?xml version="1.0" encoding="utf-16"?> 
     <ArrayOfCreateRMACriteria xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
      <CreateRMACriteria> 
       <RepairOrderId xsi:nil="true" /> 
       <RMANumber>11-11111</RMANumber> 
       <CustomerId>1111</CustomerId> 
      </CreateRMACriteria> 
     </ArrayOfCreateRMACriteriafriafriafriafriafriafriafriafriafriafriafriafriafriafriafriafriafria 
    <!-- missing '></xml>' --> 

回答

2

你不关闭(因此冲洗)的zip流,直到你上传后。我怀疑这可能是问题所在。移动此行using声明创建/使用/关闭GZipStream

FTPPut(ftpPutPath, outStream.ToArray()); 

...并获得完全摆脱Seek通话。 ToArray不需要它,并且代码中没有合适的位置来调用它。 (如果在刷新并关闭GZipStream之前调用它,它将修正数据;如果以后调用它,则会在MemoryStream关闭时失败。)顺便说一下,如果需要倒回一个流,我建议使用stream.Position = 0;作为一个更简单的选择。

+0

谢谢乔恩。将outStream.ToArray()移出使用块之外的技巧。你不需要寻求也是正确的。这是从我传输流到FTP而不是字节的剩余时间。我建议一个小的编辑,因为它不是查找是否应该被删除,但它必须被删除,否则会抛出一个封闭的流异常。 – Derpy 2014-12-04 16:29:31

+0

@TobinChee:谢谢 - 我已经编辑了相应的答案。 – 2014-12-04 17:28:41