using System;
using System.IO;
using WHC.OrderWater.Commons;
namespace Commons.File
{
/// <summary>
/// 常用的目录操作辅助类
/// </summary>
public class DirectoryUtil
{
#region 目录可写与空间计算
/// <summary>
///检查目录是否可写,如果可以,返回True,否则False
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool IsWriteable(string path)
{
if (!Directory.Exists(path))
{
param name // if the directory is not exist
try
{
// if you can create a new directory it's mean you have write right
Directory.CreateDirectory(path);
}
catch
{
return false;
}
}
try
{
string testFileName = ".test." + Guid.NewGuid().ToString().Substring(0 5);
string testFilePath = Path.Combine(path testFileName);
System.IO.File.WriteAllLines(testFilePath new string[] { "test" });
System.IO.File.Delete(testFilePath);
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 检查磁盘是否有足够的可用空间
/// </summary>
/// <param name="path"></param>
/// <param name="requiredSpace"></param>
/// <returns></returns>
public static bool IsDiskSpaceEnough(string path ulong requiredSpace)
{
string root = Path.GetPathRoot(path);
ulong freeSpace = GetFreeSpace(root);
return requiredSpace <= freeSpace;
}
/// <summary>
/// 获取驱动盘符的可用空间大小
/// </summary>
/// <param name="driveName">Direve name</param>
/// <returns>free space (byte)</returns>
public static ulong GetFreeSpace(string driveName)
{
ulong freefreeBytesAvailable = 0;
try
{
DriveInfo drive = new DriveInfo(driveName);
freefreeBytesAvailable = (ulong)drive.AvailableFreeSpace;
}
catch
{
}
return freefreeBytesAvailable;
}
public static ulong ConvertByteCountToKByteCount(ulong byteCount)
{
return byteCount / 1024;
}
public static float ConvertKByteCountToMByteCount(ulong kByteCount)
{
return kByteCount / 1024;
}
public static float ConvertMByteCountToGByteCount(float kByteCount)
{
return kByteCount / 1024;
}
#endregion
#region 目录操作
#region 获取指定目录中的文件列表
/// <summary>
/// 获取指定目录中所有文件列表
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
public static string[] GetFileNames(string directoryPath)
{
//如果目录不存在,则抛出异常
if (!IsExistDirectory(directoryPath))
{
throw new FileNotFoundException();
}
//获取文件列表
return Directory.GetFiles(directoryPath);
}
/// <summary>
/// 获取指定目录及子目录中所有文件列表
/// </summary>
/// <param name="directoryPath">指定目录的绝对路径</param>
/// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
/// 范例:"Log*.xmxxxxl"表示搜索所有以Log开头的xmxxxxl文件。</param>
/// <param name="isSearchChild">是否搜索子目录</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);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论