c# - How to copy a Stream from the begining irrespective its current position -


i got file stream has content read disk.

    stream input = new filestream("filename"); 

this stream passed third party library after reading stream, keeps stream's position pointer @ end of file (as ususal).

my requirement not load file desk everytime, instead want maintain memorystream, used everytime.

    public static void copystream(stream input, stream output)     {         byte[] buffer = new byte[32768];         int read;         while ((read = input.read(buffer, 0, buffer.length)) > 0)         {             output.write(buffer, 0, read);         }     } 

i have tried above code. works first time copy input stream output stream, subsequent calls copystream not work source's position @ end of stream after first call.

are there other alternatives copy content of source stream stream irrespective of source stream's current position.

and code needs run in thread safe manner in multi threaded environment.

you should check input stream's canseek property. if returns false, can read once anyway. if canseek returns true, can set position 0 , copy away.

if (input.canseek) {     input.position = 0; } 

you may want store old position , restore after copying.

eta: passing same instance of stream around not safest thing do. e.g. can't sure stream wasn't disposed when back. i'd suggest copy filestream memorystream in beginning, store byte content of latter calling toarray(). when need pass stream somewhere, create new 1 each time new memorystream(byte[]).