欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

遍历目录删除文件

程序员文章站 2022-05-15 09:19:10
...
/// <summary>
        /// 遍历目录删除文件
        /// </summary>
        /// <param name="dir">目录</param>
        /// <param name="isSubDir">是否包括子目录</param>
        private void DeleteDirectory(string dir, bool isSubDir)
        {
            DirectoryInfo dinfo = new DirectoryInfo(dir);
            try
            {
                foreach (FileSystemInfo item in dinfo.EnumerateFileSystemInfos())
                {
                    FileAttributes attr = item.Attributes & FileAttributes.Directory;
                    if (attr == FileAttributes.Directory)
                    {
                        if (isSubDir)
                            DeleteDirectory(item.FullName, isSubDir);
                    }
                    else
                        item.Delete();
                }
                dinfo.Delete();
            }
            catch (UnauthorizedAccessException ep)
            {

            }
            catch (IOException ep)
            {

            }
            catch (Exception ep)
            {

            }
        }