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);
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);
}
}
}
}