Copy/Delete/Permission directory
using System;
using System.IO;
using System.Security.AccessControl;
namespace Bruce.Lib
{
public class DirHelper
{
/// <summary>
/// 複製目錄
/// </summary>
/// <param name="sourcePath">來源目錄</param>
/// <param name="destPath">目地目錄</param>
/// <param name="overWrite">覆蓋原檔</param>
/// <param name="copyPermission">覆複目錄權限</param>
public static void CopyDirectory(string sourcePath, string destPath, bool overWrite, bool copyPermission)
{
DirectoryInfo sourceInfo = new DirectoryInfo(sourcePath);
DirectoryInfo targetInfo = new DirectoryInfo(destPath);
if (sourceInfo.Exists)
{
if (!targetInfo.Exists)
{
if (copyPermission)
targetInfo.Create(sourceInfo.GetAccessControl());
else
targetInfo.Create();
}
DirectoryInfo[] directories = sourceInfo.GetDirectories();
foreach (DirectoryInfo directory in directories)
{
CopyDirectory(directory.FullName, directory.FullName.Replace(sourceInfo.FullName, targetInfo.FullName), overWrite, copyPermission);
}
FileInfo[] files = sourceInfo.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(file.FullName.Replace(sourceInfo.FullName, targetInfo.FullName), overWrite);
}
}
else { throw new ArgumentException("Directory is not exist."); }
}
/// <summary>
/// 刪除目錄
/// </summary>
/// <param name="path">目錄錄徑</param>
public static void DeleteDirectory(string path)
{
DirectoryInfo info = new DirectoryInfo(path);
if (info.Exists)
{
DirectoryInfo[] directories = info.GetDirectories();
foreach (DirectoryInfo directory in directories)
{
DeleteDirectory(directory.FullName);
directory.Delete(true);
}
FileInfo[] files = info.GetFiles();
foreach (FileInfo file in files)
{
if (file.Exists)
{
file.Attributes = FileAttributes.Normal;
file.Delete();
}
}
info.Delete(true);
}
}
/// <summary>
/// 複製目錄權限
/// </summary>
/// <param name="source">來源目錄</param>
/// <param name="target">目的目錄</param>
public static void CopyDirectoryPermission(string source, string target)
{
DirectoryInfo sourceInfo = new DirectoryInfo(source);
DirectoryInfo targetInfo = new DirectoryInfo(target);
if (!sourceInfo.Exists || !targetInfo.Exists) throw new ArgumentException("Directory is not exist.");
if (sourceInfo.FullName != sourceInfo.Root.FullName && targetInfo.FullName != targetInfo.Root.FullName)
{
DirectorySecurity sourceSecurity = sourceInfo.GetAccessControl();
AuthorizationRuleCollection acl = sourceSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
DirectorySecurity targetSecurity = targetInfo.GetAccessControl();
foreach (FileSystemAccessRule rule in acl)
{
targetSecurity.AddAccessRule(rule);
}
targetInfo.SetAccessControl(targetSecurity);
}
}
}
}