110,529
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread thread;//构造线程
OpenFileDialog op;//构造对话框
private void addfile_Click(object sender, EventArgs e)
{
op = new OpenFileDialog();
op.InitialDirectory = @"d:\";//对话框打开时初始化目录
op.Filter = "All files (*.*)|*.*|txt files (*.txt)|*.txt";//文件过滤
op.RestoreDirectory = true;//保存当前目录
if (op.ShowDialog() == DialogResult.OK)
{
this.listBox1.Items.Add(op.FileName.ToString());//把选择的文件添加到listbox中
}
}
private void start_Click(object sender, EventArgs e)//用线程开始删除指定目录下的文件
{
if (this.listBox1.SelectedItem.ToString().LastIndexOf(".") > 0)//是否是文件
{
File.Delete(this.listBox1.SelectedItem.ToString());
}
else//是否是文件夹
{
thread = new Thread(new ParameterizedThreadStart(DeleteFiles));//委托线程调用带参数的方法
thread.IsBackground = true;
thread.Start(this.listBox1.SelectedItem.ToString()); //执行删除方法
}
}
public void DeleteFiles(object state)//定义一个删除文件的方法
{
string strDir = state as string;
while (true)
{
Thread.Sleep(3000);
if (Directory.Exists(strDir))//判断指定的目录是否存在
{
string[] strFiles = Directory.GetFiles(strDir);//获取该目录下的所有文件
string filenameslog= "";//用来保存删除记录
foreach (string strFile in strFiles)
{
File.Delete(strFile);
filenameslog += strFile;
this.textBox1.Text = filenameslog + "\n";//在这出错了
//错误信息:线程间操作无效: 从不是创建控件“textBox1”的线程访问它。
//原因是线程不同步
}
}
}
}
private void listBox1_DragDrop(object sender, DragEventArgs e)
{
if(e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] MyFiles;
int i;
// 将文件赋给一个数组。
MyFiles = (string[])(e.Data.GetData(DataFormats.FileDrop));
// 循环处理数组并将文件添加到列表中。
for(i = 0;i <= MyFiles.Length - 1;i++)
{
this.listBox1.Items.Add(MyFiles[i]);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.listBox1.AllowDrop = true;
}
private void listBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.All;
}
}
private void stop_Click(object sender, EventArgs e)
{
if (thread != null)
{
thread.Abort();
}
}
private void removefile_Click(object sender, EventArgs e)
{
if(this.listBox1.SelectedIndex>-1)//是否选中
{
for (int i = 0; i < this.listBox1.Items.Count;i++ )
{
this.listBox1.Items.Remove(this.listBox1.Items[i]);
}
}
}
}
Control.CheckForIllegalCrossThreadCalls = false;
this.textBox1.BeginInvoke(txt, new object[1] { filenameslog });