Dan Hall Dan Hall - 2 months ago 6
C# Question

Intercepting a filestream...Impossible?

No doubt this isn't possible but i would like to see if anyone has an ingenious suggestion. We have a third party assembly which can output an image stored internally within a bespoke database to file using an internal method 'SaveToFile', an example:

3rdParty.Scripting.ImageManager man = new 3rdParty.Scripting.ImageManager("ref");

3rdParty.Scripting.Image itemImg = man.GetImage(orderNumber);

itemImg.SaveToFile("c:\file.jpg")


ItemImg.SaveToFile has no return type and just creates a bitmap internally and writes that to a filestream. We have absolutely no access to the compiled method.

What i need to do is somehow intercept the filestream and read the bitmap, i know this probably isn't possible but i'm no absolute expert so wanted to see if there is a magical way to do this.

If all else fails i'll save the file then read it back, i just want to avoid saving to disk where i might be able to obtain the data directly and eventually convert that to a base64 string value.

Answer

Unfortunately unless the 3rd party library provides a SaveToStream method where you could provide the stream from the outside there's no way to achieve what you are after. You will have to save the contents to a temporary file and then read the contents back.

That's why it's usually best practice when designing a library to provide methods taking Streams as I/O parameters as this would give the consumer the control of whether he wants to save it to a file, memory or network stream.