When canceling the operation WriteAsyncin the thread created HttpWebRequest.GetRequestStream(), I get a WebException with the following message:
Cannot close stream until all bytes are written
How to clear my HttpWebRequestand my thread when I canceled an operation using CancellationToken?
Here is the PART of my working code (I cleared some headers for this post so the request could be garbled):
public async Task<bool> UploadAsync(FileInfo fi, CancellationToken ct, IProgress<int> progress = null)
{
FileStream fs = new FileStream(fi.FullName, FileMode.Open);
int bufferSize = 1 * 1024 * 1024;
byte[] buffer = new byte[bufferSize];
int len;
long position = fs.Position;
long totalWrittenBytes = 0;
HttpWebRequest uploadRequest = null;
Stream putStream = null;
try
{
while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
{
uploadRequest = (HttpWebRequest)WebRequest.Create("http://myuploadUrl");
uploadRequest.Method = "PUT";
uploadRequest.AddRange(position, position + len - 1);
uploadRequest.ContentLength = len;
putStream = uploadRequest.GetRequestStream();
int posi = 0;
int bytesLeft = len;
int chunkSize;
while (bytesLeft > 0)
{
chunkSize = Math.Min(25 * 1024, bytesLeft);
await putStream.WriteAsync(buffer, posi, chunkSize, ct);
bytesLeft -= chunkSize;
posi += chunkSize;
totalWrittenBytes += chunkSize;
if (progress != null)
progress.Report((int)(totalWrittenBytes * 100 / fs.Length));
}
putStream.Close();
putStream = null;
position = fs.Position;
var putResponse = (HttpWebResponse)uploadRequest.GetResponse();
putResponse.Close();
uploadRequest = null;
}
}
catch (OperationCanceledException ex)
{
if (putStream != null)
{
putStream.Flush();
putStream.Close();
}
return false;
}
finally{
fs.Close();
}
return true;
}
Guish source
share