Byte-Oriented: Write to a file

image_pdfimage_print

using System;
using System.IO;
class WriteToFile {
public static void Main(string[] args) {
FileStream fout;

try {
fout = new FileStream(“test.txt”, FileMode.Create);
} catch(IOException exc) {
Console.WriteLine(exc.Message + ”
Error Opening Output File”);
return;
}

// Write the alphabet to the file.
try {
for(char c = 'A'; c <= 'Z'; c++) fout.WriteByte((byte) c); } catch(IOException exc) { Console.WriteLine(exc.Message + "File Error"); } fout.Close(); } } [/csharp]

Byte-Oriented File input and output

image_pdfimage_print


   
 

using System;
using System.IO;

class ShowFile {
  public static void Main(string[] args) {
    int i;
    FileStream fin;

    try {
      fin = new FileStream("test.cs", FileMode.Open);
    } catch(FileNotFoundException exc) {
      Console.WriteLine(exc.Message);
      return;
    } catch(IndexOutOfRangeException exc) {
      Console.WriteLine(exc.Message + "
Usage: ShowFile File");
      return;
    }

    // read bytes until EOF is encountered
    do {
      try {
        i = fin.ReadByte();
      } catch(Exception exc) {
        Console.WriteLine(exc.Message);
        return;
      }
      if(i != -1) Console.Write((char) i);
    } while(i != -1);

    fin.Close();
  }
}
           
         
     


Checks if the input byte array contains only safe values, the data does not need to be encoded for use with LDIF

image_pdfimage_print
   
 

/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc.  www.novell.com
* 
* Permission is hereby granted, free of charge, to any person obtaining  a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including  without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
* copies of the Software, and to  permit persons to whom the Software is 
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in 
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Utilclass.Base64.cs
//
// Author:
//   Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//

using System;

namespace Novell.Directory.Ldap.Utilclass
{
  
  /// <summary> The Base64 utility class performs base64 encoding and decoding.
  /// 
  /// The Base64 Content-Transfer-Encoding is designed to represent
  /// arbitrary sequences of octets in a form that need not be humanly
  /// readable.  The encoding and decoding algorithms are simple, but the
  /// encoded data are consistently only about 33 percent larger than the
  /// unencoded data.  The base64 encoding algorithm is defined by
  /// RFC 2045.
  /// </summary>
  public class Base64
  {    
    /// <summary> Checks if the input byte array contains only safe values, that is,
    /// the data does not need to be encoded for use with LDIF.
    /// The rules for checking safety are based on the rules for LDIF
    /// (Ldap Data Interchange Format) per RFC 2849.  The data does
    /// not need to be encoded if all the following are true:
    /// 
    /// The data cannot start with the following byte values:
    /// <pre>
    /// 00 (NUL)
    /// 10 (LF)
    /// 13 (CR)
    /// 32 (SPACE)
    /// 58 (:)
    /// 60 (LESSTHAN)
    /// Any character with value greater than 127
    /// (Negative for a byte value)
    /// </pre>
    /// The data cannot contain any of the following byte values:
    /// <pre>
    /// 00 (NUL)
    /// 10 (LF)
    /// 13 (CR)
    /// Any character with value greater than 127
    /// (Negative for a byte value)
    /// </pre>
    /// The data cannot end with a space.
    /// 
    /// </summary>
    /// <param name="bytes">the bytes to be checked.
    /// 
    /// </param>
    /// <returns> true if encoding not required for LDIF
    /// </returns>
    [CLSCompliantAttribute(false)]
    public static bool isLDIFSafe(sbyte[] bytes)
    {
      int len = bytes.Length;
      if (len > 0)
      {
        int testChar = bytes[0];
        // unsafe if first character is a NON-SAFE-INIT-CHAR
        if ((testChar == 0x00) || (testChar == 0x0A) || (testChar == 0x0D) || (testChar == 0x20) || (testChar == 0x3A) || (testChar == 0x3C) || (testChar < 0))
        {
          // non ascii (>127 is negative)
          return false;
        }
        // unsafe if last character is a space
        if (bytes[len - 1] == &#039; &#039;)
        {
          return false;
        }
        // unsafe if contains any non safe character
        if (len > 1)
        {
          for (int i = 1; i < bytes.Length; i++)
          {
            testChar = bytes&#91;i&#93;;
            if ((testChar == 0x00) || (testChar == 0x0A) || (testChar == 0x0D) || (testChar < 0))
            {
              // non ascii (>127 is negative)
              return false;
            }
          }
        }
      }
      return true;
    }
    }
}

   
     


Bit Array To Byte Array

image_pdfimage_print
   
 
//http://isotopescreencapture.codeplex.com/
//The MIT License (MIT)
namespace Isotope.Collections
{
    public static class BitArrayUtil
    {
        public static byte[] BitArrayToBytes(System.Collections.BitArray bitarray)
        {
            if (bitarray.Length == 0)
            {
                throw new System.ArgumentException("must have at least length 1", "bitarray");
            }

            int num_bytes = bitarray.Length / 8;
            
            if (bitarray.Length % 8 != 0)
            {
                num_bytes += 1;
            }

            var bytes = new byte[num_bytes];
            bitarray.CopyTo(bytes, 0);
            return bytes;
        }
    }
}

   
     


Bit Array To Byte Array

image_pdfimage_print
   
 
//http://isotopescreencapture.codeplex.com/
//The MIT License (MIT)
namespace Isotope.Collections
{
    public static class BitArrayUtil
    {
        public static byte[] BitArrayToBytes(System.Collections.BitArray bitarray)
        {
            if (bitarray.Length == 0)
            {
                throw new System.ArgumentException("must have at least length 1", "bitarray");
            }

            int num_bytes = bitarray.Length / 8;
            
            if (bitarray.Length % 8 != 0)
            {
                num_bytes += 1;
            }

            var bytes = new byte[num_bytes];
            bitarray.CopyTo(bytes, 0);
            return bytes;
        }
    }
}

   
     


Reinitializes a byte array to the given value in an optimized way: byteArraySet

image_pdfimage_print

/*
* CVS identifier:
*
* $Id: ArrayUtil.java,v 1.10 2000/09/05 09:25:15 grosbois Exp $
*
* Class: ArrayUtil
*
* Description: Utillities for arrays.
*
*
*
* COPYRIGHT:
*
* This software module was originally developed by Raphaël Grosbois and
* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
* Centre France S.A) in the course of development of the JPEG2000
* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
* software module is an implementation of a part of the JPEG 2000
* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
* Systems AB and Canon Research Centre France S.A (collectively JJ2000
* Partners) agree not to assert against ISO/IEC and users of the JPEG
* 2000 Standard (Users) any of their rights under the copyright, not
* including other intellectual property rights, for this software module
* with respect to the usage by ISO/IEC and Users of this software module
* or modifications thereof for use in hardware or software products
* claiming conformance to the JPEG 2000 Standard. Those intending to use
* this software module in hardware or software products are advised that
* their use may infringe existing patents. The original developers of
* this software module, JJ2000 Partners and ISO/IEC assume no liability
* for use of this software module or modifications thereof. No license
* or right to this software module is granted for non JPEG 2000 Standard
* conforming products. JJ2000 Partners have full right to use this
* software module for his/her own purpose, assign or donate this
* software module to any third party and to inhibit third parties from
* using this software module for non JPEG 2000 Standard conforming
* products. This copyright notice must be included in all copies or
* derivative works of this software module.
*
* Copyright (c) 1999/2000 JJ2000 Partners.
*
*
*
*/
using System;
namespace CSJ2K.j2k.util
{

///

This class contains a colleaction of utility static methods for arrays.
///
///

public class ArrayUtil
{

///

The maximum array size to do element by element copying, larger
/// arrays are copyied in a n optimized way.
///

public const int MAX_EL_COPYING = 8;

///

The number of elements to copy initially in an optimized array copy

public const int INIT_EL_COPYING = 4;

///

Reinitializes a byte array to the given value in an optimized way. If
/// the length of the array is less than MAX_EL_COPYING, then the array
/// is set element by element in the normal way, otherwise the first
/// INIT_EL_COPYING elements are set element by element and then
/// System.arraycopy is used to set the other parts of the array.
///
///

/// The array to set.
///
/// /// The value to set the array to.
///
///
///
/// public static void byteArraySet(byte[] arr, byte val)
{
int i, len, len2;

len = arr.Length;
// Set array to 'val' in an optimized way
if (len < MAX_EL_COPYING) { // Not worth doing optimized way for (i = len - 1; i >= 0; i–)
{
// Set elements
arr[i] = val;
}
}
else
{
// Do in optimized way
len2 = len >> 1;
for (i = 0; i < INIT_EL_COPYING; i++) { // Set first elements arr[i] = val; } for (; i <= len2; i <<= 1) { // Copy values doubling size each time Array.Copy(arr, 0, arr, i, i); } if (i < len) { // Copy values to end Array.Copy(arr, 0, arr, i, len - i); } } } } } [/csharp]

Save Byte Array To 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 void SaveBytesToFile(string filename, byte[] bytesToWrite)
        {
            if (filename != null &amp;&amp; filename.Length > 0 &amp;&amp; bytesToWrite != null)
            {
                if (!Directory.Exists(Path.GetDirectoryName(filename)))
                    Directory.CreateDirectory(Path.GetDirectoryName(filename));

                FileStream file = File.Create(filename);

                file.Write(bytesToWrite, 0, bytesToWrite.Length);

                file.Close();
            }
        }
    }
}