C#遍历文件和文件夹

C#遍历文件和文件夹(获取和删除)

using System;
using System.IO;
using System.Linq;
using System.Text;

namespace ItemDemo
{
    class Program
    {
        private static FileStream fs;
        private static StreamWriter sw;

        static void Main(string[] args)
        {
            string path = @"C:\Program Files";

            //判断是否存在此路径文件
            if (!Directory.Exists(path))
            {
                Console.WriteLine($"不存在该路径:{path},文件");
            }
            StringBuilder sb = new StringBuilder();
            //递归文件夹获取文件
            DirectoryList(path, sb);
            //递归删除文件(小心使用)
            //DelDirectoryList(path);
            Console.WriteLine(sb.ToString());
            Console.ReadKey();

        }

        /// 
        /// 获取文件夹下所有文件
        /// 
        /// 
        /// 返回描述
        private static void GetFiless(string path, StringBuilder sb)
        {
            DirectoryInfo theFolder = new DirectoryInfo(path);
            sb.AppendLine($"=============={path}路径下文件==================");
            //遍历文件
            foreach (FileInfo file in theFolder.GetFiles())
            {
                sb.AppendLine($"{file.Name}");
            }

        }


        /// 
        /// 遍历文件夹获取文件
        /// 
        /// 
        /// 返回描述
        private static void DirectoryList(string path, StringBuilder sb)
        {
            DirectoryInfo theFolder = new DirectoryInfo(path);
            //遍历文件
            GetFiless(path, sb);

            //遍历文件夹
            foreach (DirectoryInfo directorie in theFolder.GetDirectories())
            {
                GetFiless(directorie.FullName, sb);
            }
        }

        /// 
        /// 递归遍历删除文件夹获取文件
        /// 
        /// 
        private static void DelDirectoryList(string path)
        {
            DirectoryInfo theFolder = new DirectoryInfo(path);
            var files = theFolder.GetFiles();//获取文件夹下文件
            foreach (var file in files)
            {
                //可添加删除条件,比如时间
                var time = DateTime.Now.AddDays(-7);//此处保留的一周最新编辑的文件
                if (time < file.LastWriteTime)
                {
                    file.Delete();
                }
            }
            //遍历该文件夹下的文件夹
            var dirs = theFolder.GetDirectories();
            if (!dirs.Any())
                return;
            foreach (var dir in dirs)
            {
                DelDirectoryList(dir.FullName);
            }
        }
    }
}

你可能感兴趣的:(IO文件操作,c#,File,遍历文件夹)