此文记录的是目录工具类。
/***
目录工具类
Austin Liu 刘恒辉
Project Manager and Software Designer
E-Mail: lzhdim@163.com
Blog: http://lzhdim.cnblogs.com
Date: 2024-01-15 15:18:00
***/
namespace Lzhdim.LPF.Utility
{
using System.IO;
/// <summary>
/// The Object End of Directory
/// </summary>
public static class DirUtil
{
/// <summary>
/// 复制指定目录到另一个目录(包括子目录和所有文件)
/// </summary>
/// <param name="sourceDir">源目录</param>
/// <param name="targetDir">目标目录</param>
/// <exception cref="DirectoryNotFoundException"></exception>
public static void CopyDirectory(string sourceDir, string targetDir)
{
DirectoryInfo dir = new DirectoryInfo(sourceDir);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: {sourceDir}");
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = Path.Combine(targetDir, file.Name);
file.CopyTo(tempPath, false);
}
// If copying subdirectories, copy them and their contents to the new location.
foreach (DirectoryInfo subdir in dirs)
{
string tempPath = Path.Combine(targetDir, subdir.Name);
CopyDirectory(subdir.FullName, tempPath);
}
}
/// <summary>
/// Create a dir
/// </summary>
/// <param name="dir">dir which need to create</param>
/// <returns>true dir is create;false dir is create error</returns>
public static bool CreateDir(string dir)
{
if (!Directory.Exists(dir))
{
try
{
Directory.CreateDirectory(dir);
return true;
}
catch
{ }
return false;
}
return true;
}
/// <summary>
/// Delete a dir
/// </summary>
/// <param name="dir">dir which need to delete</param>
/// <returns>true dir is delete;false dir is delete error</returns>
public static bool DeleteDir(string dir)
{
if (Directory.Exists(dir))
{
try
{
Directory.Delete(dir);
return true;
}
catch
{ }
return false;
}
return false;
}
/// <summary>
/// Check if dir is exist
/// </summary>
/// <param name="dir">dir which need to check</param>
/// <returns>true dir is exist;false dir is not exist</returns>
public static bool DirIsExist(string dir)
{
return Directory.Exists(dir);
}
/// <summary>
/// rename a dir
/// </summary>
/// <param name="srcDir">dir which need to rename</param>
/// <param name="desDir">the renamed dir name</param>
/// <returns>true rename is done;false rename is error</returns>
public static bool RenameDir(string srcDir, string desDir)
{
try
{
Directory.Move(srcDir, desDir);
return true;
}
catch
{ }
return false;
}
}
}