Reads a stream into a byte array.

image_pdfimage_print
   
 
#region License

/*
 * Copyright  2002-2005 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#endregion
using System;
using System.IO;

namespace Spring.Util
{
    /// <summary>
    /// Utility methods for IO handling
    /// </summary>
    internal sealed class IOUtils
    {
        private IOUtils()
        {
            throw new InvalidOperationException("instantiation not supported");
        }

        /// <summary>
        /// Reads a stream into a byte array. 
        /// </summary>
        /// <remarks>
        /// Does not close the input stream!
        /// </remarks>
        public static byte[] ToByteArray(Stream src)
        {
            MemoryStream stm = new MemoryStream();
            CopyStream(src, stm);
            stm.Close();
            return stm.ToArray();
        }

        /// <summary>
        /// Copies one stream into another. 
        /// (Don&#039;t forget to call <see cref="Stream.Flush"/> on the destination stream!)
        /// </summary>
        /// <remarks>
        /// Does not close the input stream!
        /// </remarks>
        public static void CopyStream(Stream src, Stream dest)
        {
            int bufferSize = 2048;
            byte[] buffer = new byte[bufferSize];

            int bytesRead = 0;
            while ((bytesRead = src.Read(buffer, 0, bufferSize)) > 0)
            {
                dest.Write(buffer, 0, bytesRead);
            }
        }
    }
}

   
     


This entry was posted in File Stream. Bookmark the permalink.