ASP.NET删除指定目录下的所有文件及其文件夹
方法一
string origraphurl = "UploadImages/" + number + "_" + createtimestamp;//活动原图存放的路径
string thumbnailurl = "ThumbNail/" + number + "_" + createtimestamp;//活动缩略图存放的路径
string file1 = context.Server.MapPath(origraphurl);
string file2 = context.Server.MapPath(thumbnailurl);
Directory.Delete(file1, true);
log.Info("删除活动所有原图及其所在的文件夹");
Directory.Delete(file2, true);
log.Info("删除活动所有缩略图及其所在的文件夹");
方法二
方法体
///删除指定目录下的所有文件及其文件夹
/// <param name="file">文件夹路径</param>
public static void DeleteDir(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//如果有子文件删除文件
File.Delete(f);
}
else
{
//循环递归删除子文件夹
DeleteDir(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
}
catch (Exception ex) // 异常处理
{
log.Error(ex);//捕获异常,将异常写入日志
}
}
调用方法
string origraphurl = "UploadImages/" + number + "_" + createtimestamp;//活动原图存放的路径
string thumbnailurl = "ThumbNail/" + number + "_" + createtimestamp;//活动缩略图存放的路径
string file1 = context.Server.MapPath(origraphurl);
string file2 = context.Server.MapPath(thumbnailurl);
DeleteDir(file1);
log.Info("删除活动所有原图及其所在的文件夹");
DeleteDir(file2);
log.Info("删除活动所有缩略图及其所在的文件夹");