I need to read a bunch of files from disk, archive them on the fly and send to the Web API zipped from Memory stream. But every time I get error Cannot close stream until all bytes are written.
My code works fine if I save zip file to local disk and then open FileStream and send it to the WebAPI, But I need to do it on the fly without saving. Here is my code:
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());
}
}
}
}
The error
"Cannot close stream until all bytes are written"
is at client.PostAsync("Log/PostLog", content).Result;
If I repalce MemoryStream mZip with FileStream this code saves proper zip file so I suppose there is no problem with contenet length.
If I close ZipOutputStream zipOStream before sending then MemoryStream mZip is also closed and can not be sent. What is wrong?