C#/.NET 删除某个文件夹(及其子文件夹)中指定文件名的文件

        private void BtnDelete_Click(object sender, EventArgs e)
        {           
            List<string> nameList = new List<string>()
            {
                "xxx1",
                "xxx2",
                "xxx3",
                "xxx4",
                "xxx5",
            };
            Task.Run(() =>
            {
            	//文件路径放在textBox1中即可
                nameList.ForEach(x => DelLicenseFiles(textBox1.Text, x));
            }).ContinueWith(x=> {
                MessageBox.Show("删除完成");
            });
        }
        /// <summary>
        /// 删除指定文件夹下指定文件名的文件
        /// </summary>
        /// <param name="url">文件夹地址</param>
        /// <param name="name">要删除的文件名</param>--自带去除扩展名
        /// <returns></returns>
        public void DelLicenseFiles(string path, string name)
        {
            try
            {
                DirectoryInfo Folder = new DirectoryInfo(path);
                var files = Folder.GetDirectories();
                foreach (FileInfo file in Folder.GetFiles())
                {
                    if(file.Attributes != FileAttributes.Directory)
                    {
                        if (name == file.Name.Substring(0, file.Name.LastIndexOf('.')))
                        {
                            file.Delete();
                        }
                    }
                }
                foreach (var dicInfo in Folder.GetDirectories())
                {
                    DelLicenseFiles(dicInfo.FullName, name);
                }
            }
            catch
            { 

            }
        }
发布了190 篇原创文章 · 获赞 298 · 访问量 48万+

猜你喜欢

转载自blog.csdn.net/qq_34202873/article/details/99713607