public async Task WriteToStream(Stream outputStream, HttpContent content, TransportContext context) { int bytesRead = 0; byte[] buffer = null; DbConnection dbConnection = null; // In the WriteToStream method, we proceed to read the file chunks progressively from the db // and flush these bits to the output stream. try { CheckInitialized(); dbConnection = _filesRepository.CreateConnection(); dbConnection.Open(); for (int chunkNum = 1; chunkNum <= _file.ChunkCount; chunkNum++) { buffer = _filesRepository.ReadChunkContent(dbConnection, _file.FileId, chunkNum); bytesRead = buffer.Length; await outputStream.WriteAsync(buffer, 0, bytesRead); } } catch { // log error here throw; } finally { outputStream.Close(); if (dbConnection != null) { dbConnection.Close(); } buffer = null; } }