Sample of a Manager with Singleton for make a few specific IO operation
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Framework
{
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Manager i/o. </summary>
////////////////////////////////////////////////////////////////////////////////////////////////////
public class ManagerIO
{
#region singleton
/// <summary> The instance. </summary>
private static ManagerIO instance = null;
/// <summary> The padlock. </summary>
private static readonly object padlock = new object();
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Prevents a default instance of the <see cref="ManagerIO"/> class from being created.
/// </summary>
////////////////////////////////////////////////////////////////////////////////////////////////////
ManagerIO()
{
//if (_Log.IsDebugEnabled)
// _Log.DebugFormat("Nouvelle instance de {0}", Assembly.GetExecutingAssembly());
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Gets the instance. </summary>
///
/// <value> The instance. </value>
////////////////////////////////////////////////////////////////////////////////////////////////////
public static ManagerIO Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new ManagerIO();
}
return instance;
}
}
}
#endregion Gestion du singleton
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Copies the directory (with protected files). </summary>
///
/// <param name="SourcePath"> The source path. </param>
/// <param name="DestinationPath"> The destination path. </param>
/// <param name="Recursive"> if set to <c>true</c> [recursive]. </param>
///
/// <returns> true if it succeeds, false if it fails. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public Boolean CopyDirectory(string SourcePath, string DestinationPath, bool Recursive)
{
List<string> Paths = new List<string>();
List<string> Files = new List<string>();
Boolean bResult = false;
if (String.IsNullOrEmpty(SourcePath))
throw new ArgumentNullException("SourcePath");
if (String.IsNullOrEmpty(DestinationPath))
throw new ArgumentNullException("DestinationPath");
try
{
foreach (string StringPath in this.DirectoryList(SourcePath, Recursive, null))
{
Paths.Add(StringPath);
}
foreach (string StringPath in this.FileList(SourcePath, Recursive, null))
{
Files.Add(StringPath);
}
foreach (string dirPath in Paths)
{
System.IO.Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
}
foreach (string newPath in Files)
{
System.IO.File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), Recursive);
}
bResult = true;
}
catch (Exception ex)
{
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", ex);
bResult = false;
}
return bResult;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Renames the specified file. </summary>
///
/// <exception cref="ArgumentNullException"> Thrown when one or more required arguments are
/// null. </exception>
/// <exception cref="IOException"> Thrown when an IO failure occurred. </exception>
///
/// <param name="oldPath"> Full path of file to rename. </param>
/// <param name="newName"> New file name. </param>
////////////////////////////////////////////////////////////////////////////////////////////////////
public void RenameFile(string oldPath, string newName)
{
if (String.IsNullOrEmpty(oldPath))
throw new ArgumentNullException("oldPath");
if (String.IsNullOrEmpty(newName))
throw new ArgumentNullException("newName");
string oldName = Path.GetFileName(oldPath);
// if the file name is changed
if (!String.Equals(oldName, newName, StringComparison.CurrentCulture))
{
string folder = Path.GetDirectoryName(oldPath);
string newPath = Path.Combine(folder, newName);
bool changeCase = String.Equals(oldName, newName, StringComparison.CurrentCultureIgnoreCase);
// if renamed file already exists and not just changing case
if (File.Exists(newPath) && !changeCase)
{
throw new IOException(String.Format("File already exists:n{0}", newPath));
}
else if (changeCase)
{
// Move fails when changing case, so need to perform two moves
string tempPath = Path.Combine(folder, Guid.NewGuid().ToString());
Directory.Move(oldPath, tempPath);
Directory.Move(tempPath, newPath);
}
else
{
Directory.Move(oldPath, newPath);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Liste des fichier protégé ou non d'un répertoires. </summary>
///
/// <param name="RootDirectory"> The root directory. </param>
/// <param name="SearchAllDirectories"> if set to <c>true</c> [search all directories]. </param>
/// <param name="Filter"> The filter. </param>
///
/// <returns> . </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public List<string> FileList(string RootDirectory,
bool SearchAllDirectories, Predicate<string> Filter)
{
List<string> retList = new List<string>();
if (String.IsNullOrEmpty(RootDirectory))
throw new ArgumentNullException("RootDirectory");
try
{
List<string> DirList = new List<string> { RootDirectory };
if (SearchAllDirectories)
{
DirList.AddRange(this.DirectoryList(RootDirectory, SearchAllDirectories, Filter));
}
foreach (string DirectoryStr in DirList)
{
DirectoryInfo di = new DirectoryInfo(DirectoryStr);
try
{
foreach (FileInfo FileStr in di.GetFiles())
{
try
{
if ((Filter == null) || (Filter(FileStr.FullName)))
{
retList.Add(FileStr.FullName);
}
}
catch (Exception ax)
{
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", ax);
}
}
}
catch (UnauthorizedAccessException)
{
}
catch (Exception ex)
{
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", ex);
}
}
}
catch (Exception ex)
{
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", ex);
}
return retList;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Liste d'un répertoire protegé ou non. </summary>
///
/// <param name="RootDirectory"> The root directory. </param>
/// <param name="SearchAllDirectories"> if set to <c>true</c> [search all directories]. </param>
/// <param name="Filter"> The filter. </param>
///
/// <returns> . </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public List<string> DirectoryList(string RootDirectory,
bool SearchAllDirectories, Predicate<string> Filter)
{
List<string> retList = new List<string>();
if (String.IsNullOrEmpty(RootDirectory))
throw new ArgumentNullException("RootDirectory");
try
{
DirectoryInfo di = new DirectoryInfo(RootDirectory);
foreach (DirectoryInfo DirectoryStr in di.GetDirectories())
{
try
{
if ((Filter == null) || (Filter(DirectoryStr.FullName)))
{
retList.Add(DirectoryStr.FullName);
if (SearchAllDirectories)
{
retList.AddRange(this.DirectoryList(DirectoryStr.FullName, SearchAllDirectories,
Filter));
}
}
}
catch (UnauthorizedAccessException)
{
}
catch (Exception exx)
{
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", exx);
}
}
}
catch (Exception ex)
{
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", ex);
}
return retList;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Gets file as stream. </summary>
///
/// <exception cref="ArgumentNullException"> Thrown when one or more required arguments are
/// null. </exception>
///
/// <param name="psFilePath"> Full pathname of the ps file. </param>
///
/// <returns> The file as stream. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public byte[] GetFileAsStream(String psFilePath)
{
if (String.IsNullOrEmpty(psFilePath))
throw new ArgumentNullException("psFilePath");
byte[] fileContent = null;
try
{
if (File.Exists(psFilePath))
{
fileContent = File.ReadAllBytes(psFilePath);
}
}
catch (Exception ex)
{
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", ex);
}
return fileContent;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary> Saves a stream as file. </summary>
///
/// <param name="pByteArray"> Array of bytes. </param>
/// <param name="psSaveFileAs"> The ps save file as. </param>
///
/// <returns> true if it succeeds, false if it fails. </returns>
////////////////////////////////////////////////////////////////////////////////////////////////////
public Boolean SaveStreamAsFile( byte[] pByteArray, String psSaveFileAs)
{
Boolean bResult = false;
if (String.IsNullOrEmpty(psSaveFileAs))
throw new ArgumentNullException("psSaveFileAs");
try
{
// instance a memory stream and pass the
// byte array to its constructor
MemoryStream ms = new MemoryStream(pByteArray);
// instance a filestream pointing to the
// storage folder, use the original file name
// to name the resulting file
FileStream fs = new FileStream(psSaveFileAs, FileMode.Create);
// write the memory stream containing the original
// file as a byte array to the filestream
ms.WriteTo(fs);
// clean up
ms.Close();
fs.Close();
fs.Dispose();
bResult = true;
}
catch (Exception ex)
{
bResult = false;
ManagerLogger.Instance.LogException("RemoteSurvey.Tools", ex);
}
return bResult;
}
}
}