【问题标题】:Send zipped files to Web API - Error: Cannot close stream until all bytes are written将压缩文件发送到 Web API - 错误:在写入所有字节之前无法关闭流
【发布时间】:2013-09-25 20:02:39
【问题描述】:

我需要从磁盘读取一堆文件,即时归档它们并发送到从内存流压缩的 Web API。但是每次我收到错误时,在写入所有字节之前都无法关闭流。

如果我将 zip 文件保存到本地磁盘然后打开 FileStream 并将其发送到 WebAPI,我的代码工作正常,但我需要在不保存的情况下即时执行。这是我的代码:

using (MemoryStream mZip = new MemoryStream())
{
    using (ZipOutputStream zipOStream = new ZipOutputStream(mZip))
    {
        foreach (FileInfo fi in allFiles)
        {
            ZipEntry entry = new ZipEntry((fi.Name));
            zipOStream.PutNextEntry(entry);
            FileStream fs = File.OpenRead(fi.FullName);

            try
            {
                byte[] transferBuffer = new byte[1024];
                int bytesRead = 0;
                do
                {
                    bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length);
                    zipOStream.Write(transferBuffer, 0, bytesRead);
                }
                while (bytesRead > 0);
            }
            finally
            {
                fs.Close();
            }
        }

        using (var client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential(login, password) }))
        {
            using (var content = new MultipartFormDataContent())
            {
                client.BaseAddress = new Uri(AppConfig.ServerApiURL);                                
                var streamContent = new StreamContent(mZip);
                streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "Filename.zip",  Size = mZip.Length
                };

                content.Add(streamContent);
                var result = client.PostAsync("Log/PostLog", content).Result;
                MessageBox.Show(result.StatusCode.ToString());
            }
        }
    }
}

错误

“在写入所有字节之前无法关闭流”

client.PostAsync("Log/PostLog", content).Result; 如果我用 FileStream 替换 MemoryStream mZip,则此代码将保存正确的 zip 文件,因此我认为内容长度没有问题。

如果我在发送之前关闭 ZipOutputStream zipOStream,那么 MemoryStream mZip 也会关闭并且无法发送。 怎么了?

【问题讨论】:

    标签: c# .net memorystream dotnet-httpclient sharpziplib


    【解决方案1】:

    在添加到 StreamContent 之前,您必须将 Memory Stream 对象的即 mZip.Postion 设置为零,如下所示

    mZip.Position = 0 ;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2015-05-04
      • 1970-01-01
      • 2013-10-11
      相关资源
      最近更新 更多