Read file content to a byte array

   
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


    public class File
    {
        public static byte[] Read(string fileName)
        {
            byte[] buff = null;
            
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            long numBytes = new FileInfo(fileName).Length;
            buff = br.ReadBytes((int)numBytes);
            return buff;
        }

    }

   
     


Compare two files byte by byte

   
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Globalization;

    public static class File
    {
        /// Compare two files byte by byte

        public static bool Compare(string path1, string path2)
        {
            return ChecksumSha1(path1) == ChecksumSha1(path2);
        }

        public static string ChecksumSha1(string path)
        {
            byte[] hash = null;

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                hash = sha1.ComputeHash(fs);

                fs.Close();
            }

            return Convert.ToBase64String(hash);
        }
    }

   
     


Write byte array to a file

   
 


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

class Program {
    static void Main(string[] args) {
        byte[] byData;
        char[] charData;

        try {
            FileStream aFile = new FileStream("Temp.txt", FileMode.Create);
            charData = "www.kutayzorlu.com/java2s/com".ToCharArray();
            byData = new byte[charData.Length];
            Encoder e = Encoding.UTF8.GetEncoder();
            e.GetBytes(charData, 0, charData.Length, byData, 0, true);

            aFile.Seek(0, SeekOrigin.Begin);
            aFile.Write(byData, 0, byData.Length);
        } catch (IOException ex) {
            Console.WriteLine(ex.ToString());
            return;
        }
    }
}

    


Save byte array to a file

/*
Copyright (c) 2010 James Craig

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.*/

#region Usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

#endregion

namespace Utilities
{
public static class FileManager
{
///

/// Determines if a directory exists
///

/// Path of the directory /// true if it exists, false otherwise
public static bool DirectoryExists(string DirectoryPath)
{
try
{
return Directory.Exists(DirectoryPath);
}
catch (Exception a)
{
throw a;
}
}
///

/// Saves a file
///

/// File content /// File name to save this as (should include directories if applicable) /// Tells the system if you wish to append data or create a new document public static void SaveFile(byte[]Content, string FileName,bool Append)
{
FileStream Writer = null;
try
{
int Index = FileName.LastIndexOf('/');
if (Index <= 0) { Index = FileName.LastIndexOf(''); } if (Index <= 0) { throw new Exception("Directory must be specified for the file"); } string Directory = FileName.Remove(Index) + "/"; bool Opened = false; while (!Opened) { try { if (Append) { Writer = File.Open(FileName, FileMode.Append, FileAccess.Write, FileShare.None); } else { Writer = File.Open(FileName, FileMode.Create, FileAccess.Write, FileShare.None); } Opened = true; } catch (System.IO.IOException e) { throw e; } } Writer.Write(Content, 0, Content.Length); Writer.Close(); } catch (Exception a) { throw a; } finally { if (Writer != null) { Writer.Close(); Writer.Dispose(); } } } } } [/csharp]

Byte-Oriented: Write to a file

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


   
 

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

   
 

/******************************************************************************
* 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;
    }
    }
}