1. 程式人生 > >C#批量刪除指定資料夾下指定檔名的所有資料夾

C#批量刪除指定資料夾下指定檔名的所有資料夾

private void DeleteDirByName(string rootPath, string name)

        {

            string dirName = rootPath;

            if(rootPath.EndsWith("//")||rootPath.EndsWith("/"))

            {

                rootPath = rootPath.Substring(0,rootPath.Length-1);

            }

            int indexSplit = rootPath.LastIndexOf('//');

            if(indexSplit<0)

            {

                indexSplit = rootPath.LastIndexOf('/');

            }

            if(indexSplit>0)

            {

                dirName = rootPath.Substring(indexSplit + 1);

            }

            if (dirName.ToLower() == name.ToLower())

            {

                this.SetFileAttributes(rootPath);

                Directory.Delete(rootPath, true);

                this.textBox3.Text += rootPath + Environment.NewLine;

            }

            else

            {

                string[] subDirs = Directory.GetDirectories(rootPath);

                foreach (string subDir in subDirs)

                {

                    this.DeleteDirByName(subDir, name);

                }

            }

        }

        private void SetFileAttributes(string path)

        {

            string[] files = Directory.GetFiles(path);

            foreach (string file in files)

            {

                File.SetAttributes(file, FileAttributes.Normal);

            }

            string[] subDirs = Directory.GetDirectories(path);

            foreach (string subDir in subDirs)

            {

                this.SetFileAttributes(subDir);

            }

        }

原文地址:點選開啟連結