0

我需要从磁盘读取一堆文件,即时归档它们并发送到从内存流压缩的 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; If I repalce MemoryStream mZip with FileStream 此代码保存正确的 zip 文件,所以我认为内容长度没有问题。

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

4

1 回答 1

1

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

mZip.Position = 0 ;

于 2014-03-04T09:11:48.437 回答