Adding extension to Stream : Extension « Class « C# / CSharp Tutorial






using System.ComponentModel;
using System.IO;
using System.Net;


    public static class StreamUtilWithExtensions
    {
        const int BufferSize = 8192;

        public static void CopyTo(this Stream input,Stream output)
        {
            byte[] buffer = new byte[BufferSize];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }

        public static byte[] ReadFully(this Stream input)
        {
            using (MemoryStream tempStream = new MemoryStream())
            {
                CopyTo(input, tempStream);
                if (tempStream.Length == tempStream.GetBuffer().Length)
                {
                    return tempStream.GetBuffer();
                }
                return tempStream.ToArray();
            }
        }
    }



    class MainClass
    {
        static void Main()
        {
            WebRequest request = WebRequest.Create("http://java2s.com");
            using (WebResponse response = request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (FileStream output = File.Create("data.dat"))
            {
                responseStream.CopyTo(output);
            }
        }
    }








7.60.Extension
7.60.1.Adding extension method for int
7.60.2.Adding extension to Stream
7.60.3.Adding reverse operation to string
7.60.4.Add title case to string class
7.60.5.Extension Method On Null Reference
7.60.6.extension method
7.60.7.conflicting extension methods
7.60.8.Extension Methods