Builds a bracketed CSV list from the array

image_pdfimage_print

//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
* 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 the HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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.Text;
using System.Collections.Generic;

namespace EffiProz.Core.Lib
{

/** Provides a collection of convenience methods for processing and
* creating objects with String value components.
*
* @author fredt@users
* @author boucherb@users
* @version 1.7.2
* @since 1.7.0
*/
public class StringUtil
{
/**
* Builds a bracketed CSV list from the array
* @param array an array of Objects
* @return string
*/
public static String arrayToString(Object array)
{

int len = ((Array)array).Length;
int last = len – 1;
StringBuilder sb = new StringBuilder(2 * (len + 1));

sb.Append('{');

for (int i = 0; i < len; i++) { sb.Append(((Array)array).GetValue(i)); if (i != last) { sb.Append(','); } } sb.Append('}'); return sb.ToString(); } } } [/csharp]

Save a byte array content into a file.

image_pdfimage_print
   
 

#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>
        /// Save a byte array content into a file.
        /// </summary>
        /// <param name="path">The full path of the file to save</param>
        /// <param name="content">content to save in byte array</param>
        /// ---------------------------------------------------------------
        public static void Save(string path, byte[] content)
        {
            if (Path.GetDirectoryName(path).Length > 0 &amp;&amp; 
                !Directory.Exists(Path.GetDirectoryName(path)))
                throw new DirectoryNotFoundException(String.Format("The directory path &#039;{0}&#039; to save the file does not exist.", Path.GetDirectoryName(path)));

            using (FileStream writeStream = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                writeStream.Write(content, 0, content.Length);
                writeStream.Close();
            }
        }

        /// ---------------------------------------------------------------
        /// <summary>
        /// Save a char array content into a file.
        /// </summary>
        /// <param name="path">The full path of the file to save.</param>
        /// <param name="content">content to save in char array.</param>
        /// ---------------------------------------------------------------
        public static void Save(string path, char[] content)
        {
            // convert char[] to byte[]
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] byteArray = encoding.GetBytes(content);

            Save(path, byteArray);
        }

        /// ---------------------------------------------------------------
        /// <summary>
        /// Save a string content into a file.
        /// </summary>
        /// <param name="path">The full path of the file to save</param>
        /// <param name="content">content to save in string</param>
        /// ---------------------------------------------------------------
        public static void Save(string path, string content)
        {
            if (Path.GetDirectoryName(path).Length > 0 &amp;&amp;
                !Directory.Exists(Path.GetDirectoryName(path)))
                throw new DirectoryNotFoundException(String.Format("The directory path &#039;{0}&#039; to save the file does not exist.", Path.GetDirectoryName(path)));

            using (StreamWriter stream = File.CreateText(path))
            {
                stream.Write(content);
                stream.Close();
            }
        }

    }
}

   
     


Read binary context of a file.

image_pdfimage_print
   
 
#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&#039;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 &amp;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&#039;ve been passed an unhelpful initial length, just
            // use 32K.
            if (initialLength < 1)
                initialLength = Int16.MaxValue;


            byte&#91;&#93; buffer = new byte&#91;initialLength&#93;;
            int read = 0;

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

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

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

                    // Nope. Resize the buffer, put in the byte we&#039;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);
        }
    }
}

   
     


Read file content to a byte array

image_pdfimage_print
   
 
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

image_pdfimage_print
   
 
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

image_pdfimage_print
   
 


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

image_pdfimage_print

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