[C# 문법] C# 디렉토리(Directory) 년\월\일 디렉토리 구조 삭제하기
- C#/C# 문법
- 2021. 8. 3. 12:57
안녕하세요. 오늘은 C# 문법에서 디렉토리 삭제하는 방법에 대해서 알려 드리려고 합니다. 그 중에서도 일반 디렉토리 삭제가 아닌, 디렉토리 이름이 년\월\일 구조로 이루어진 디렉토리를 삭제하는 방법에 대해서 예제 코드를 통해서 어떻게 삭제하는지 보여드리려고 합니다.
디렉토리 구조
- 디렉토리 구조는 다음과 같이 이루어져 있습니다.
- Demo
- 2019
- 01
- 01
- 02
- 03
- 02
- 01
- 2020
- 01
- 01
- 02
- 01
- 2021
- 01
- 02
- 03
- 01
- 02
- 03
- 04
- 2019
- Demo
- 위와 같이 TopDirectory가 있고, 해당 경로 안에는 다시 년\월\일 구조로 이루어진 디렉토리가 있습니다.
- 이 디렉토리를 삭제 대상 날짜 기준으로 비교하여 삭제하는 방법을 예제코드를 통해 보여 드리도록 하겠습니다.
예제 코드
using System;
using System.IO;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
DateTime dt = new DateTime(2020, 6, 10);
// 년\월\일 디렉토리 삭제
DeleteDirectoriesNewFormat(dt);
}
private static void DeleteDirectoriesNewFormat(DateTime date)
{
// 년도 폴더 삭제
string path = @"C:\User\Desktop\Demo";
DeleteDirectories(path, date.Year, 4);
// 월 폴더 삭제
path = Path.Combine(path, date.Year.ToString("D4"));
DeleteDirectories(path, date.Month, 2);
// 일 폴더 삭제
path = Path.Combine(path, date.Month.ToString("D2"));
DeleteDirectories(path, date.Day, 2);
}
private static void DeleteDirectories(string targetPath, int targetValue, int dirLength)
{
string dirName = string.Empty;
if (Directory.Exists(targetPath))
{
foreach (var subPath in Directory.GetDirectories(targetPath))
{
dirName = new DirectoryInfo(subPath).Name;
if (dirName.Length != dirLength)
{
continue;
}
if (int.TryParse(dirName, out int compareValue) == false)
{
continue;
}
if (compareValue >= targetValue)
{
continue;
}
try
{
Directory.Delete(subPath, true);
}
catch { }
}
}
}
}
}
- 해당 코드를 삭제할 Directory 경로만 맞춰주고 해당 디렉토리안에 년\월\일 폴더들이 존재한다면, 삭제 날짜 기준으로 이전의 디렉토리들은 삭제되는 것을 확인할 수 있습니다.
728x90
'C# > C# 문법' 카테고리의 다른 글
[C# 문법] List<T> 클래스와 람다식 조합 (4) | 2021.08.06 |
---|---|
[C# 문법] C# Linq Zip 메서드 (0) | 2021.08.04 |
[C# 문법] C# 월별, 일별 Directory 삭제하기 (0) | 2021.07.29 |
[C# 문법] C# Directory 에서 SubDirectory(하위 디렉토리) 찾기 (0) | 2021.07.29 |
[C# 문법] C# Dictionary 같은 Key 에 여러개의 데이터 넣기 (0) | 2021.07.28 |
이 글을 공유하기