最完整的文件和目录操作
资料来源不易。。。。。
1. 检测指定目录是否存在
public static class DirFile
{
/// <summary>
/// 检测指定目录是否存在
/// </summary>
/// <param name="directoryPath">目录的绝对路径</param>
/// <returns></returns>
public static bool IsExistDirectory(string directoryPath)
{
return Directory.Exists(directoryPath);
}
2. 获取指定目录中所有文件列表
/// <summary>
/// 获取指定目录中所有文件列表
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static string[] GetFileNames(string directoryPath)
{
//如果目录不存在,则抛出异常
if (!IsExistDirectory(directoryPath))
{
throw new FileNotFoundException();
}
//获取文件列表
return Directory.GetFiles(directoryPath);
}
3. 获取指定目录中所有子目录列表
/// <summary>
/// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,使用重载方法
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static string[] GetDirectories(string directoryPath)
{
try
{
return Directory.GetDirectories(directoryPath);
}
catch (IOException ex)
{
throw ex;
}
}
4. 获取指定目录及子目录中所有文件列表
/// <summary>
/// 获取指定目录及子目录中所有文件列表
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
{
//如果目录不存在,则抛出异常
if (!IsExistDirectory(directoryPath))
{
throw new FileNotFoundException();
}
try
{
if (isSearchChild)
{
return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
}
else
{
return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
}
}
catch (IOException ex)
{
throw ex;
}
}
5. 检测指定目录是否为空
/// <summary>
/// 检测指定目录是否为空
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static bool IsEmptyDirectory(string directoryPath)
{
try
{
//判断是否存在文件
string[] fileNames = GetFileNames(directoryPath);
if (fileNames.Length > 0)
{
return false;
}
//判断是否存在文件夹
string[] directoryNames = GetDirectories(directoryPath);
if (directoryNames.Length > 0)
{
return false;
}
return true;
}
catch
{
return true;
}
}
6. 检测指定目录中是否存在指定的文件
/// <summary>
/// 检测指定目录中是否存在指定的文件
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static bool Contains(string directoryPath, string searchPattern)
{
try
{
//获取指定的文件列表
string[] fileNames = GetFileNames(directoryPath, searchPattern, false);
//判断指定文件是否存在
if (fileNames.Length == 0)
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
7. 创建目录
<