/// <summary>
/// 删除指定目录下的文件(一些静态文件,指定文件夹里面的子文件及文件)
/// </summary>
/// <param name="dir">指定目录,比如:"D://3333"</param>
public static void DeleteFolder(string dir)
{
int lens = 0;
string str = "";
try
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
{
lens = d.LastIndexOf(".") + 1;
str = d.Substring(lens, (d.Length - lens)).ToLower();
string[] strs = ConfigurationManager.AppSettings["FileEndName"].ToString().Split(',');
for (int i = 0; i < strs.Length;i++ )
{
if (str == strs[i])
{
FileInfo fi = new FileInfo(d);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
File.Delete(d);//直接删除其中的文件
nums++;
}
}
}
else
{
lens = d.LastIndexOf("//") + 1;
str = d.Substring(lens, d.Length - lens).ToLower();
string[] files = ConfigurationManager.AppSettings["FileName"].ToString().Split(',');
int aa = 0;
for (int j = 0; j < files.Length;j++ )
{
if (str == files[j])//删除文件夹为指定名称的所有内容
{
DeleteFolder1(d);
FileNum++;
aa++;
}
}
if (aa == 0)
{
DeleteFolder(d);//递归删除子文件夹
}
}
}
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dir);
if (di.GetFiles().Length + di.GetDirectories().Length == 0)
{
Directory.Delete(dir);//删除已空文件夹
FileNum++;
}
}
catch(Exception ex)
{
MessageBox.Show("删除失败!");
MessageBox.Show(ex.ToString());
}
}
/// <summary>
/// 删除指定文件及里面所有的子项
/// </summary>
/// <param name="dir"></param>
public static void DeleteFolder1(string dir)
{
try
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
{
FileInfo fi = new FileInfo(d);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
File.Delete(d);//直接删除其中的文件
nums++;
}
else
DeleteFolder1(d);//递归删除子文件夹
}
Directory.Delete(dir);//删除已空文件夹
FileNum++;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}