//This file is part of ORM.NET.
//
//ORM.NET 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.
//
//ORM.NET 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 ORM.NET; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.ComponentModel;
namespace OrmLib{
/// <summary>
/// Provides static functions to maipulate files.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public class FileTools
{
private FileTools(){}
/// <summary>
/// Copys the contents of a file into a string.
/// </summary>
/// <param name="fileName">The file to use.</param>
/// <returns>The contents of the file.</returns>
public static string ToString( string fileName)
{
FileStream fs = new FileStream( fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
StreamReader sr = new StreamReader( fs, Encoding.GetEncoding("ISO-8859-1"));
String fileData = sr.ReadToEnd();
sr.Close();
fs.Close();
return fileData;
}
/// <summary>
/// Copys the contents of a file into a Byte Array.
/// </summary>
/// <param name="fileName">The file to use.</param>
/// <returns>The contents of the file.</returns>
public static byte[] ToByteArray( string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read );
BinaryReader br = new BinaryReader(fs);
byte[] data = br.ReadBytes( (int)fs.Length);
br.Close();
fs.Close();
return data;
}
/// <summary>
/// Reads a configuration file, converting into it's Hashtable representation.
/// </summary>
/// <param name="fileName">The file to use.</param>
/// <returns>The Hashtable of key/value pairs.</returns>
public static Hashtable ToConfigMap(String fileName)
{
FileStream fs = new FileStream( fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite );
StreamReader sr = new StreamReader( fs );
String fileData = sr.ReadToEnd();
Regex r = new Regex(@"(?<key>[^=]*)=(?<value>.*)\r\n");
Match m = r.Match( fileData );
Hashtable h = new Hashtable();
while (m.Length > 0)
{
h.Add( m.Groups["key"].ToString(), m.Groups["value"].ToString() );
m = m.NextMatch();
}
return h;
}
/// <summary>
/// One-liner to create a new file, or overwrite the contents of an existing file.
/// </summary>
/// <param name="fileName">The full path to the file</param>
/// <param name="newData">The data to write to the file.</param>
public static void OverwriteFile(string fileName, string newData)
{
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter( fs );
sw.Write(newData);
sw.Close();
fs.Close();
}
/// <summary>
/// One-liner to create a new file, or overwrite the contents of an existing file.
/// </summary>
/// <param name="fileName">The full path to the file</param>
/// <param name="newData">The data to write to the file.</param>
public static void OverwriteFile(string fileName, byte[] newData)
{
FileStream fs = new FileStream( fileName, FileMode.Create, FileAccess.Write, FileShare.None);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write( newData );
bw.Close();
fs.Close();
}
/// <summary>
/// Creates a file, if it does not exist, and populates it with
/// the given data.
/// </summary>
/// <param name="fileName">The file to create</param>
/// <param name="data">The data to fill the file with</param>
public static void CreateFileNoOverWrite(string fileName, string data)
{
byte[] b = ASCIIEncoding.ASCII.GetBytes( data );
CreateFileNoOverWrite(fileName,b);
}
/// <summary>
/// Creates a file, if it does not exist, and populates it with
/// the given data.
/// </summary>
/// <param name="fileName">The file to create</param>
/// <param name="data">The data to fill the file with</param>
public static void CreateFileNoOverWrite(string fileName, byte[] data)
{
if ( ! File.Exists(fileName) )
{
FileStream fs = File.Create(fileName);
fs.Write(data,0,data.Length);
fs.Close();
}
}
/// <summary>
/// Converts a file that was compiled into an Assembly onto a stream.
/// </summary>
/// <param name="fileName">The file that was compiled in.</param>
/// <param name="executingAssembly">The assembly it was compiled into.</param>
/// <returns>The stream reprentation of the file.</returns>
public static Stream Resource2Stream(string fileName, Assembly executingAssembly)
{
return executingAssembly.GetManifestResourceStream( fileName.Replace(@"\",".") );
}
/// <summary>
/// Converts a file that was compiled into an Assembly onto a byte array.
/// </summary>
/// <param name="fileName">The file that was compiled in.</param>
/// <param name="executingAssembly">The assembly it was compiled into.</param>
/// <returns>The byte reprentation of the file.</returns>
public static byte[] Resource2ByteArray(string fileName, Assembly executingAssembly)
{
fileName = fileName.Replace (@"\", @".");
Stream stream = Resource2Stream(fileName, executingAssembly);
if (stream != null)
{
byte[] bytes = new Byte[stream.Length];
for (long i = 0; i < stream.Length; i++)
bytes[i] = (byte)stream.ReadByte();
stream.Close();
return bytes;
}
return null;
}
/// <summary>
/// Converts a file that was compiled into an Assembly onto a string.
/// </summary>
/// <param name="fileName">The file that was compiled in.</param>
/// <param name="executingAssembly">The assembly it was compiled into.</param>
/// <returns>The string reprentation of the file.</returns>
public static string Resource2String(string fileName, Assembly executingAssembly)
{
return ASCIIEncoding.ASCII.GetString(Resource2ByteArray(fileName, executingAssembly));
}
/// <summary>
/// Load a CSV file, and parse it into an array of type.
/// </summary>
/// <param name="fileName">The full path of the CSV file to parse.</param>
/// <param name="colSeparator">The character that delimits the columns, usually a comma.</param>
/// <param name="type">The Data Type to load each row from the CSV into.</param>
/// <returns>An array of type, where each row is mapped into a single instance of type.</returns>
public static ArrayList CsvToArrayOfTypedStruct( string fileName, char colSeparator, System.Type type)
{
// load the file.. if it has no data, return an empty array
string fileData = ToString(fileName);
if (fileData == null || fileData.Length == 0) return new ArrayList();
// get rid of the carriage returns, just leave linefeeds to split on..
fileData = fileData.Replace("\r", "");
string[] rows = fileData.Split( '\n');
// load each row into an array of column values, and add to arrayCols
ArrayList arrayCols = new ArrayList();
foreach(string col in rows)
{
if (col != null && col.Length > 0)
{
string[] cols = col.Split(colSeparator);
arrayCols.Add(cols);
}
}
// prepare a result array, and enumerate through each row
ArrayList arrayResults = new ArrayList();
foreach(string[] col in arrayCols)
{
// for each row, create an object of type type, to store the data from the row
Object o = type.GetConstructor( new Type[0] ).Invoke(new object[0]);
FieldInfo[] fi = type.GetFields();
for(int i = 0; i < col.Length; i++)
{
if (col[i].Length > 0)
{
if (fi[i].FieldType.IsEnum )
{
// for enums, parse the string value into the enum
//Debug.WriteLine(fi[i].FieldType.FullName);
fi[i].SetValue(o, Enum.Parse( fi[i].FieldType, col[i], true));
}
else
fi[i].SetValue(o, col[i]);
}
}
if (col.Length > 0)
arrayResults.Add( o);
}
return arrayResults;
}
}
}
|