Read binary context of a file. : Byte Read Write « File Stream « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# Book
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » File Stream » Byte Read WriteScreenshots 
Read binary context of a file.
 
#region License and Copyright
/* -------------------------------------------------------------------------
 * Dotnet Commons IO
 *
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 
 * for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this library; if not, write to the 
 
 * Free Software Foundation, Inc., 
 * 59 Temple Place, 
 * Suite 330, 
 * Boston, 
 * MA 02111-1307 
 * USA 
 
 * -------------------------------------------------------------------------
 */
#endregion

using System;
using System.Collections;
using System.Globalization;
using System.IO;

namespace Dotnet.Commons.IO
{

    ///  
    /// <summary>  
    /// This class provides basic facilities for manipulating files and file paths.
    /// 
    /// <h3>File-related methods</h3>
    /// There are methods to 
    /// <list type="bullet">
    ///     <item>copy a file to another file,</item>
    ///     <item>compare the content of 2 files,</item>
    ///     <item>delete files using the wildcard character,</item>
    ///     <item>etc</item>
    /// </list>
    /// </summary>
    ///     
    public sealed class FileUtils
    {
        /// <summary>
        /// Reads data from the beginning of a stream until the end is reached. The
        /// data is returned as a byte array. 
        /// </summary>
        /// <param name="stream">The stream to read data from</param>
        /// <exception cref="IOException">thrown if any of the underlying IO calls fail</exception>
        /// <remarks>Use this method if you don't know the length of the stream in advance 
        /// (for instance a network stream) and just want to read the whole lot into a buffer. 
        /// <para>
        /// <strong>Note:</strong><br/>
        /// This method of reading the stream is not terribly efficient.
        /// </para>
        ///  </remarks>
        public static byte[] GetBytes(Stream stream)
        {
            if (stream is MemoryStream)
                return ((MemoryStream)stream).ToArray();

            byte[] byteArray = new byte[1024];
            using (MemoryStream ms = new MemoryStream())
            {
                stream.Position = 0;
                while (true)
                {
                    int readLen = stream.Read(byteArray, 0, byteArray.Length);
                    if (readLen <= 0)
                        return ms.ToArray();
                    ms.Write(byteArray, 0, readLen);
                }
            }
        }
        /// <summary>
        /// Reads data from a stream until the end is reached. The
        /// data is returned as a byte array. 
        /// </summary>
        /// <param name="stream">The stream to read data from</param>
        /// <param name="initialLength">The initial buffer length. If the length is &lt; 1,
        /// then the default value of <see cref="Int16.MaxValue"/> will be used.
        /// </param>
        /// <exception cref="IOException">thrown if any of the underlying IO calls fail</exception>
        /// <remarks>Use this method to get the data if you know the expected length of data to start with.</remarks>
        public static byte[] GetBytes(Stream stream, long initialLength)
        {
            // If we've been passed an unhelpful initial length, just
            // use 32K.
            if (initialLength < 1)
                initialLength = Int16.MaxValue;


            byte[] buffer = new byte[initialLength];
            int read = 0;

            int chunk;
            while ((chunk = stream.Read(buffer, read, buffer.Length - read)) 0)
            {
                read += chunk;

                // If we've reached the end of our buffer, check to see if there's
                // any more information
                if (read == buffer.Length)
                {
                    int nextByte = stream.ReadByte();

                    // End of stream? If so, we're done
                    if (nextByte == -1)
                    {
                        return buffer;
                    }

                    // Nope. Resize the buffer, put in the byte we've just
                    // read, and continue
                    byte[] newBuffer = new byte[buffer.Length * 2];
                    Array.Copy(buffer, newBuffer, buffer.Length);
                    newBuffer[read(byte)nextByte;
                    buffer = newBuffer;
                    read++;
                }
            }
            // Buffer is now too big. Shrink it.
            byte[] ret = new byte[read];
            Array.Copy(buffer, ret, read);
            return ret;
        }
        /// ---------------------------------------------------------------
        /// <summary>
        /// Read binary context of a file.
        /// </summary>
        /// <param name="path">Full path (directory + filename) of file to read</param>
        /// <returns>content in byte array</returns>
        /// ---------------------------------------------------------------
        public static byte[] ReadBinaryFile(string path)
        {
            FileInfo fi = new FileInfo(path);
            byte[] data = null;

            if (!fi.Exists)
                throw new IOException(path + " does not exists");

            // Read File 
            using (Stream stream = File.OpenRead(path))
            {
                // Get Data from The Stream
                data = GetBytes(stream, fi.Length);

                // Close Stream
                stream.Close();
            }

            fi.Refresh();

            // Return Data
            return (data);
        }
    }
}

   
  
Related examples in the same category
1.Byte-Oriented File input and outputByte-Oriented File input and output
2.Byte-Oriented: Write to a file
3.Save byte array to a file
4.Write byte array to a file
5.Compare two files byte by byte
6.Read file content to a byte array
7.Save a byte array content into a file.
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.