C# winfrom遍历指定目录下的所有文件,并删除指定文件

时间:2022-10-29 12:52:27

看着那些人写的都是些只能得到指定目录下的文件信息,觉得没什么用处,自己写了个,我写的可以得到整个D盘下的所有文件信息。 

 private void button2_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Add("D:\\");
            for (int i = 0; i < listBox1.Items.Count; i++)
            {


                DirectoryInfo TheFolder = new DirectoryInfo(listBox1.Items[i].ToString());

                try
                {
                    foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())
                    {
                        try
                        {
                            this.listBox1.Items.Add(NextFolder.FullName);

                        }
                        catch (Exception)
                        {


                        }

                    }
                }
                catch (Exception)
                {


                }
                //遍历文件夹

                //遍历文件
                try
                {
                    foreach (FileInfo NextFile in TheFolder.GetFiles())
                    {
                        try
                        {
                            if (NextFile.Name.ToString() == "20120301184117.png")
                            {
                                System.IO.FileInfo file = new System.IO.FileInfo(NextFile.FullName);
                                if (file.Exists)
                                {
                                    file.Delete();
                                }

                            }


                            this.listBox2.Items.Add(NextFile.Name);

                        }
                        catch (Exception)
                        {


                        }

                    }
                }
                catch (Exception)
                {


                }

            }
        }