using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
namespace Deployer.Logic
{
class FileSystemUtil
{
///
/// Wraps File class enabling coping of folders
///
/// Source path
/// Destination path
public static void CopyFolder(string source, string dest)
{
if (!dest.EndsWith("\\"))
dest += "\\";
if (!Directory.Exists(dest))
Directory.CreateDirectory(dest);
foreach (string file in Directory.GetFiles(source))
{
string fileDestionation = dest + Path.GetFileName(file);
CopyFile(file, fileDestionation);
}
foreach (string folder in Directory.GetDirectories(source))
{
string subFolder = Path.GetFileName(folder);
CopyFolder(folder, dest + "\\" + subFolder);
}
}
///
/// Copy folder with option to exclude some folders/files
///
/// Source path
/// Destination path
/// List of strings of folders/files to exclude. If it is folder it must not end with \\ in order to have successful comparison
public static void CopyFolderWithExclude(string source, string dest, List excludePaths)
{
if (excludePaths.Contains(source.TrimEnd('\\')))
return;
if (!dest.EndsWith("\\"))
dest += "\\";
if (!Directory.Exists(dest))
Directory.CreateDirectory(dest);
foreach (string file in Directory.GetFiles(source))
{
string fileDestionation = dest + Path.GetFileName(file);
if (!excludePaths.Contains(file))
CopyFile(file, fileDestionation);
}
foreach (string folder in Directory.GetDirectories(source))
{
string subFolder = Path.GetFileName(folder);
CopyFolderWithExclude(folder, dest + "\\" + subFolder, excludePaths);
}
}
///
/// Wraps File.Copy method because of read only and system files
///
/// Path to file
/// Path to file
public static void CopyFile(string source, string destionation)
{
if (File.Exists(destionation))
File.Delete(destionation);
File.Copy(source, destionation);
}
///
/// Delete file from disk even if it is temporary taken by some other program
///
/// Path to file
public static void DeleteFile(string filePath)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(deleteFileProcess), filePath);
}
private static void deleteFileProcess(object o)
{
try
{
File.Delete(o.ToString());
}
catch
{
Thread.Sleep(5000);
deleteFileProcess(o);
return;
}
}
///
/// Reading file from disk with silent failing if it is taken
///
/// Path to file
/// FileInfo if file is successfuly read, null if it is not
public static FileInfo TryToReadFile(string filePath)
{
try
{
File.ReadAllBytes(filePath);
return new FileInfo(filePath);
}
catch
{
return null;
}
}
///
/// Deletes all content from folder
///
/// Path to folder
public static void ClearFolder(DirectoryInfo dir)
{
foreach (DirectoryInfo di in dir.GetDirectories())
di.Delete();
foreach (FileInfo fi in dir.GetFiles())
fi.Delete();
}
}
}