using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace WinAppDemo.Forms
{
public partial class DeleteForm : Form
{
public int cur = 0;
public int ccc = 0;
public int fileNum = 0;
public string FilePath = "";
//1定义委托类型
public delegate void MyDelegate(int value, string s);//在定义委类型的同时,定义函数的参数
//2声明委托变量
MyDelegate md;
public DeleteForm(string path)
{
InitializeComponent();
//3实例化委托类型
md = new MyDelegate(setValue);
FilePath = path;
}
public void setValue(int value, string s)
{
if (value >= fileNum)
{
value = fileNum;
}
this.progressBar1.Value = value;
//this.label1.Text = string.Format("{0}:{1}", "正在删除", s);
this.label1.Text = string.Format("{0}:{1}", "正在删除", FilePath);
if (value == fileNum) this.Close();
}
public void step_forward2(object obj)//删除指定文件夹下的所有文件和文件夹
{
deleteDir(FilePath);
}
private void deleteDir(string file_path)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file_path);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file_path, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file_path))
{
foreach (string f in Directory.GetFileSystemEntries(file_path))
{
if (File.Exists(f))//如果f代表的是文件
{
//File.Delete(f);
cur++;
//如果有子文件删除文件
if (this.IsHandleCreated)
{
this.progressBar1.Invoke(md, cur, f);//跨线程调用
}
new FileInfo(f).Attributes = FileAttributes.Normal;//为了解决访问被拒绝的问题
File.Delete(f);
}
else//如果f代表的是目录
{
//循环递归删除子文件夹
//Console.WriteLine("开始递归删除文件夹:" + f);
deleteDir(f);
}
}
Directory.Delete(file_path);
}
}
catch (Exception ex) // 异常处理
{
Console.WriteLine("删除文件异常:" + ex.Message.ToString());// 异常信息
}
}
public int GetFilesCount(System.IO.DirectoryInfo dirInfo)
{
//System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(dirPath);
int totalFile = 0;
totalFile += dirInfo.GetFiles().Length;
foreach (System.IO.DirectoryInfo subdir in dirInfo.GetDirectories())
{
totalFile += GetFilesCount(subdir);
}
return totalFile;
}
private void DeleteForm_Load(object sender, EventArgs e)
{
cur = 0;
if (Directory.Exists(FilePath) == false)
{
this.Close();
return;
}
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(FilePath);
fileNum = GetFilesCount(dirInfo);//获取所有文件的个数
//Console.WriteLine(fileNum + "-----------------------------------");
this.progressBar1.Maximum = fileNum;
this.progressBar1.Minimum = 0;
Thread thr = new Thread(new ParameterizedThreadStart(step_forward2));
thr.Start();
}
}
}
调用的时候,直接把调用放在一个线程中
Task t1 = new Task(() =>
{
DeleteForm de = new DeleteForm(casePath);
de.ShowDialog();
});
t1.Start();