views:

241

answers:

1

How can I clone FileStream type?

The problem is that I using MagickNet.Image(inputStream) to get the image distentions before saving it, but it seems to closing the inputStream.

So, I can send a clone of inputStream to the function, so the function cannot edit the real inputStream object?

This is my function:

public Picture GetPictureDimension(Stream inputStream, Picture picture)
{
    var img = new MagickNet.Image(inputStream);

    picture.Width = img.Columns;
    picture.Height = img.Rows;

    return picture;
}
+2  A: 

You could just re-open the file? But to keep a single Stream without it getting closed, you could try NonClosingStreamWrapper in MiscUtil. Just be sure to reset the Position if appropriate.

Marc Gravell
I don't really sure that MagickNet.Image close the stream, as it is lacking documentation, but I do sure that after this function, the `readStream.Read` return zero bytes. So, I the first thing that I think how to debug this is to creat a clone of the stream type, but after looking how to do that it seems not trivial task. So this ring the question how do we cloning types like this one?
Mendy
Read will do that if the stream position is at the end. It most likely just read to the end of the stream.
Josh Einstein
If it was a closed stream, Read would throw.
Josh Einstein
@Mendy - in that case, are you sure it isn't just at the end of the stream? Try setting `theStream.Position = 0;` before calling `Read(...)`.
Marc Gravell
@Josh: you are right. @Marc: Thanks. But can you answer the question, do we can clone this types of objects in c#?
Mendy
@Mendy - because the source of the stream is *external* and unmanaged, there is not going to be a managed way to clone it.
Marc Gravell
@Marc: Just to make it close. What thinks I can do, to clone this variable in .net. Can I use c++ for this?
Mendy
@Mendy - I wouldn't have thought so, no. You would ultimately be doing the same thing as opening the file twice - you'd need two underlying file handles. So either open it twice or rewind it.
Marc Gravell