I have a web service with a download functionality in an ApiController derived class. It reads a local file and passes it to a PushStreamContent, which cares for delivery to the requesting client. This works mostly fine, but sometimes I get an exception which I don't understand in the call to outputStream.Write().
It says "System.Net.ProtocolViolationException: 'Bytes to be written to the stream exceed the Content-Length bytes size specified.'" and it comes mostly when I access a file, which is being opened for write by another process (where this process might append something, but in the situation of exception this doesn't need to happen). Anyhow this shouldn't matter because the file was successfully opened here and the last part was successfully read into my buffer.
response.Content = new PushStreamContent((Stream outputStream, HttpContent content, TransportContext context) =>
{
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var buffer = new byte[65536];
var length = (int)stream.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = stream.Read(buffer, 0, Math.Min(length, buffer.Length));
outputStream.Write(buffer, 0, bytesRead);
length -= bytesRead;
}
}
},
"text/plain");
Note: In the debugger I see the outputStream is of type HttpResponseStream, it uses an InnerStream of type HttpListenerStreamWrapper.
So any idea what goes wrong and how I can fix it?