Reading stream twice?
Asked Answered
R

2

41

When I have uploaded an image from my website I need to do 2 things:

  1. read the image dimensions
  2. save the image to the database

the first thing I do is reading the image stream into an Image object, like so:

var file = Request.Files["logo"];

Image FullsizeImage = Image.FromStream(file.InputStream);

the next thing I do is to save the "file" object to the database (LINQ to SQL). BUT, when I try to save the image to database, the stream from the file has it's postion at the end of the stream, and it seems no data is present.

I know I should somwhow reset the stream and put it back into position 0, but how do I do that the most effiecent and correct way ?

Reynaud answered 24/11, 2010 at 11:56 Comment(0)
G
83

Well, the simplest way is:

file.InputStream.Position = 0;

... assuming the stream supports seeking. However, That may do interesting things to the Image if you're not careful - because it will have retained a reference to the stream.

You may be best off loading the data into a byte array, and then creating two separate MemoryStream objects from it if you still need to. If you're using .NET 4, it's easy to copy one stream to another:

MemoryStream ms = new MemoryStream();
Request.Files["logo"].InputStream.CopyTo(ms);
byte[] data = ms.ToArray();
Geld answered 24/11, 2010 at 11:59 Comment(2)
do you mean file.InputStream.Position = 0; ?Reynaud
@danielovich: Yes, I did - sorry, fixed.Geld
B
2

In addition to Jon's answer: If you have a StreamReader, there is no Position parameter - instead you need to access its BaseStream.

For this purpose you can use a little extension method ResetStreamReader:

public static class Extension
{
    public static void ResetStreamReader(this StreamReader sr, long position = 0)
    {
        if (sr == null) return;
        sr.BaseStream.Position = position;
    }
}

Put it inside your public static Extension class, then you can use it like so:

sr.ResetStreamReader();

Or you can pass the desired start position, if you want to start with a position > 0, for example if you want to skip headers when you read the stream again.

Betatron answered 15/12, 2020 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.