/// <Summary> /// Convert stream to byte [] /// </Summary> Public Byte [] Streamtobytes (Stream stream ){ Byte [] Bytes = New Byte [Stream. Length]; stream. Read (bytes, 0 , Bytes. Length ); // Set the current stream position to the beginning of the stream Stream. Seek ( 0 , Seekorigin. Begin ); Return Bytes ;} /// <Summary> /// Convert byte [] to stream /// </Summary> Public Stream bytestostream ( Byte [] Bytes) {stream = New Memorystream (bytes ); Return Stream ;} /* --* Conversion between stream and files *-------- --------------- */ /// <Summary> /// Write stream to file /// </Summary> Public Void Streamtofile (Stream stream,String Filename ){ // Convert stream to byte [] Byte [] Bytes = New Byte [Stream. Length]; stream. Read (bytes, 0 , Bytes. Length ); // Set the current stream position to the beginning of the stream Stream. Seek ( 0 , Seekorigin. Begin ); // Write byte [] to a file Filestream FS = New Filestream (filename, filemode. Create); binarywriter BW = New Binarywriter (FS); BW. Write (bytes); BW. Close (); FS. Close ();} /// <Summary> /// Read stream from File /// </Summary> Public Stream filetostream ( String Filename ){ // Open a file Filestream = New Filestream (filename, filemode. Open, fileaccess. Read, fileshare. Read ); // Read byte of the object [] Byte [] Bytes = New Byte [Filestream. Length]; filestream. Read (bytes, 0 , Bytes. Length); filestream. Close (); // Convert byte [] to stream Stream stream = New Memorystream (bytes ); Return Stream ;}
Reprinted from: http://www.cnblogs.com/poissonnotes/archive/2010/03/12/1684187.html