Home > front end >  Calling OpenReadStream of an IFormFile multiple times
Calling OpenReadStream of an IFormFile multiple times

Time:01-05

I need to have the stream of the file in 2 different locations. In the code the IFormFile is already passed as parameter in the 2 methods. I thought of either modifying the methods and calling the OpenReadStream in the beginning and pass the stream as param or calling OpenReadStream separately.

I inspected the dissasembled code and OpenReadStream does this:

return new ReferenceReadStream(_baseStream, _baseStreamOffset, Length);

and the ReferenceReadStream class does this in the constructor:

public ReferenceReadStream(Stream inner, long offset, long length)
{
    if (inner == null)
    {
        throw new ArgumentNullException("inner");
    }
    _inner = inner;
    _innerOffset = offset;
    _length = length;
    _inner.Position = offset;
}

In my understanding the base stream is the same and it doesn't matter calling OpenReadStream multiple times.

What worries me is if I'll run into problems when I start using Seek method.

Does anyone know what's the correct usage of OpenReadStream in this senario?

CodePudding user response:

Apparently it's not safe to call OpenReadStream multiple times.

When Read method is called, it calls this method:

private void VerifyPosition()
    {
        if (_inner.Position == _innerOffset   _position)
        {
            return;
        }
        throw new InvalidOperationException("The inner stream position has changed unexpectedly.");
    }

I was able to trigger this exception with the following code:

var s = file.OpenReadStream();
s.Seek(10, SeekOrigin.Begin);
var b = new byte[2];
var c = s.Read(b);
var s2 = file.OpenReadStream();
c = s.Read(b);
  • Related