FTP + GZipStream ='文件被破坏'拉开拉链时

时间:2014-12-03 22:47:28

标签: c# .net ftp gzip gzipstream

我正在尝试使用GZipStream在上传到FTP服务器之前压缩文档。如果我在上传之前将压缩文件流保存到磁盘,则本地文件系统上的副本是正确的。但是,当我尝试在FTP服务器上解压缩文件时,我得到了一个“文件已损坏”的文件。来自7zip的错误。生成的解压缩文件是正确的,直到重复一系列字符时的最后几个字符。我尝试了许多不同的配置但无济于事。

    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>' -->

1 个答案:

答案 0 :(得分:2)

您尚未关闭(并因此刷新)zip流,直到之后上传了它。我怀疑这可能是问题所在。 创建/使用/关闭using的{​​{1}}语句后,将此行移至

GZipStream

...完全摆脱FTPPut(ftpPutPath, outStream.ToArray()); 电话。 Seek并不需要它,并且您的代码中没有合适的点来调用它。 (如果您在刷新并关闭ToArray之前调用它,它将更正数据;如果您之后调用它,它将在GZipStream关闭时失败。)顺便说一下,当你需要回放一个流,我建议使用MemoryStream作为更简单的替代方案。