Read Stream to Byte array

image_pdfimage_print
   
 
///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace WOSI.Utilities
{
    public class FileUtils
    {





        public static byte[] GetStreamBytes(Stream stream)
        {
            try
            {
                stream.Position = 0;
            }
            catch
            {
            }

            byte[] readBuffer = new byte[1024];
            List<byte> outputBytes = new List<byte>();

            int offset = 0;

            while (true)
            {
                int bytesRead = stream.Read(readBuffer, 0, readBuffer.Length);

                if (bytesRead == 0)
                {
                    break;
                }
                else if (bytesRead == readBuffer.Length)
                {
                    outputBytes.AddRange(readBuffer);
                }
                else
                {
                    byte[] tempBuf = new byte[bytesRead];

                    Array.Copy(readBuffer, tempBuf, bytesRead);

                    outputBytes.AddRange(tempBuf);

                    break;
                }

                offset += bytesRead;
            }

            return outputBytes.ToArray();
        }
   }
}

   
     


Read byte array from file

image_pdfimage_print
   
 

///////////////////////////////////////////////////////////////////////////////////////////////
//
//    This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
//    Copyright (c) 2005-2008, Jim Heising
//    All rights reserved.
//
//    Redistribution and use in source and binary forms, with or without modification,
//    are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright notice,
//      this list of conditions and the following disclaimer in the documentation and/or
//      other materials provided with the distribution.
//
//    * Neither the name of Jim Heising nor the names of its contributors may be
//      used to endorse or promote products derived from this software without specific prior
//      written permission.
//
//    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//    IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//    POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace WOSI.Utilities
{
    public class FileUtils
    {

        public static byte[] GetFileBytes(string filename)
        {
           if (File.Exists(filename))
            {
                FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read);

                byte[] fileBytes = new byte[fs.Length];

                fs.Read(fileBytes, 0, (int)fs.Length);

                fs.Close();

                return fileBytes;
            }

            return null;
        }
   }
}

   
     


Write a byte array to a file

image_pdfimage_print
   
 
//http://tinyerp.codeplex.com/
//GNU Library General Public License (LGPL)
//-----------------------------------------------------------------------
// <copyright file="SysUtil.cs" company="Pyramid Consulting">
//     Copyright (c) Pyramid Consulting. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;

namespace Bamboo.Core.Common
{
    public class SysUtil
    {
        /// <summary>
        /// write a byte array to a file
        /// </summary>
        /// <param name="strFilePath">dest file path</param>
        /// <param name="bContent">content to write</param>
        /// <returns>return 0 on succeed,otherwise throw a exception</returns>
        public static int WriteFile(String strFilePath, byte[] bContent)
        {
            System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
            try
            {
                bw.Write(bContent);
            }
            finally
            {
                bw.Close();
                fs.Close();
            }
            return 0;
        }
    }
}

   
     


Get the byte array from a string using default encoding

image_pdfimage_print
   
 
//http://tinyerp.codeplex.com/
//GNU Library General Public License (LGPL)
//-----------------------------------------------------------------------
// <copyright file="SysUtil.cs" company="Pyramid Consulting">
//     Copyright (c) Pyramid Consulting. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;

namespace Bamboo.Core.Common
{
    public class SysUtil
    {
        /// <summary>
        /// get the byte array from a string using default encoding
        /// </summary>
        /// <param name="strData">source string</param>
        /// <returns>converted array</returns>
        public static byte[] StringToBytes(String strData)
        {
            return System.Text.Encoding.GetEncoding(0).GetBytes(strData);
        }
    }
}

   
     


Convert a byte array to string using default encoding

image_pdfimage_print
   
 


//http://tinyerp.codeplex.com/
//GNU Library General Public License (LGPL)
//-----------------------------------------------------------------------
// <copyright file="SysUtil.cs" company="Pyramid Consulting">
//     Copyright (c) Pyramid Consulting. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;

namespace Bamboo.Core.Common
{
    public class SysUtil
    {
        /// <summary>
        /// convert a byte array to string using default encoding
        /// </summary>
        /// <param name="bData">the content of the array</param>
        /// <returns>converted string</returns>
        public static String BytesToString(byte[] bData)
        {
            return System.Text.Encoding.GetEncoding(0).GetString(bData);
        }
    }
}

   
     


illustrates use of BufferedStreams

image_pdfimage_print
   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_14.cs illustrates use of BufferedStreams
*/

using System;
using System.Windows.Forms;
using System.IO;

public class Example15_14 
{
    [STAThread]
  public static void Main() 
  {

    // use an open file dialog to get a filename
    OpenFileDialog dlgOpen = new OpenFileDialog();
    dlgOpen.Title="Select file to back up";

    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
      // create the raw streams
      FileStream inStream = File.OpenRead(dlgOpen.FileName);
      FileStream outStream = 
        File.OpenWrite(dlgOpen.FileName + ".bak");

      // add a buffering layer
      BufferedStream bufInStream = new BufferedStream(inStream);
      BufferedStream bufOutStream = new BufferedStream(outStream);

      byte[] buf = new byte[4096];
      int bytesRead;

      // copy all data from in to out via the buffer layer
      while ((bytesRead = bufInStream.Read(buf, 0, 4096)) > 0)
        bufOutStream.Write(buf, 0, bytesRead);

      // clean up
      bufOutStream.Flush();
      bufOutStream.Close();
      bufInStream.Close();
      outStream.Close();
      inStream.Close();

    }

  }

}



           
          


Create a FileStream for the BufferedStream.

image_pdfimage_print

using System;
using System.IO;

class BufStreamApp
{
static void Main(string[] args)
{
FileStream fs = new FileStream(“Hoo.txt”,FileMode.Create, FileAccess.ReadWrite);
BufferedStream bs = new BufferedStream(fs);
Console.WriteLine(“Length: {0} Position: {1}”,bs.Length, bs.Position);

for (int i = 0; i < 64; i++) { bs.WriteByte((byte)i); } Console.WriteLine("Length: {0} Position: {1}", bs.Length, bs.Position); byte[] ba = new byte[bs.Length]; bs.Position = 0; bs.Read(ba, 0, (int)bs.Length); foreach (byte b in ba) { Console.Write("{0,-3}", b); } string s = "Foo"; for (int i = 0; i < 3; i++) { bs.WriteByte((byte)s[i]); } Console.WriteLine(" Length: {0} Position: {1} ",bs.Length, bs.Position); for (int i = 0; i < (256-67)+1; i++) { bs.WriteByte((byte)i); } Console.WriteLine(" Length: {0} Position: {1} ", bs.Length, bs.Position); bs.Close(); } } [/csharp]