C# Directory 클래스 로 디렉토리 작업 튜토리얼

소개

운영 체제에서 폴더는 파일과 하위 폴더를 저장합니다. C# 및 .NET의 Directory 클래스는 폴더를 다루는 기능을 제공합니다. 이 포스트에서는 폴더의 속성을 읽는 방법, 폴더의 크기 및 파일 수를 가져오는 방법, 폴더를 만드는 방법, 하위 폴더를 만드는 방법, 폴더 내의 모든 파일을 반복적으로 열거하는 방법, 폴더를 이동하는 방법 및 폴더를 삭제하는 방법에 대해 다룹니다.

이전 포스팅 DirectoryInfo 클래스와 다른점은 정적 선언으로 디렉토리를 다룬다는거 외에는 사용법이 같습니다. Directory 클래스는 인스턴스를 만들거나 new 로 초기화 하지 않고 바로 사용하다는 간편한 방식입니다. 디렉토리를 다룰때 이 클래스가 가장 많이 사용됩니다.

C# Directory 클래스

.NET Framework의 C# Directory 클래스는 디렉토리 및 하위 디렉토리를 만들고 복사, 이동 및 삭제하는 정적 메서드를 제공합니다. Directory 클래스를 사용하려면 먼저 System.IO 네임스페이스를 가져와야 합니다.

using System.IO;

폴더 만들기

Directory.CreateDirectory 메서드는 지정된 경로에 디렉토리 또는 폴더를 만듭니다. 원격 컴퓨터에도 디렉토리를 만들 수 있습니다.

다음 코드는 디렉토리가 이미 존재하지 않는 경우 D:\ 드라이브에 Temp 폴더를 만듭니다.

string root = @"D:\Temp";
// 디렉토리가 존재하지 않으면 만듭니다.
if (!Directory.Exists(root))
{
    Directory.CreateDirectory(root);
}

Directory.CreateDirectory는 하위 디렉토리 또는 하위 폴더도 만듭니다. 하위 디렉토리가 만들어질 폴더의 경로를 지정하기만 하면 됩니다. 다음 코드는 D:\Temp 디렉토리에 ‘Haro’ 하위 디렉토리를 만듭니다.

string subdir = @"D:\Temp\Haro";
// 하위 디렉토리 만들기
if (!Directory.Exists(subdir))
{
    Directory.CreateDirectory(subdir);
}

폴더 삭제하기

Directory.Delete 메서드는 지정된 경로에서 비어 있는 폴더를 영구적으로 삭제합니다. 폴더에 하위 폴더와 파일이 있는 경우 폴더를 삭제하기 전에 이러한 하위 폴더 및 파일을 삭제해야 합니다. 비어 있지 않은 파일을 삭제하려고 시도하면 오류 메시지가 표시됩니다.

다음 코드는 대상 폴더를 삭제합니다.

string root = @"D:\Temp\Haro";
// 디렉토리가 존재하지 않으면 시도하지 않습니다.
if (Directory.Exists(root))
{
    Directory.Delete(root);
}

다음 코드는 폴더에 하위 디렉토리 및 파일이 있는지 확인하고 폴더를 삭제하기 전에 이러한 하위 디렉토리 및 파일을 삭제합니다.

Directory.Exists 메서드는 지정된 디렉토리가 있는지 확인합니다. 다음 코드는 디렉토리가 존재하는지 확인하고 디렉토리가 존재하는 경우에만 삭제합니다.

string root = @"D:\Temp";
// 디렉토리가 존재하지 않으면 시도하지 않습니다.
if (Directory.Exists(root))
{
    Directory.Delete(root);
}

폴더 이동하기

Directory.Move 메서드는 기존 디렉토리를 새 경로에 있는 디렉토리로 이동합니다. Move 메서드는 두 개의 매개 변수를 사용합니다. 먼저 Move 메서드는 원래 디렉토리를 삭제합니다.

다음 코드는 원본 디렉토리를 대상 디렉토리로 이동합니다.

string sourceDirName = @"D:\Temp";
string destDirName = @"D:\NewTemp";
try
{
    Directory.Move(sourceDirName, destDirName);
}
catch (IOException exp)
{
    Console.WriteLine(exp.Message);
}

폴더 복사하기

디렉토리를 복사하는 메서드는 없습니다. 디렉토리를 복사하려면 이동할 디렉토리로 이동하고 하위 디렉토리와 파일을 복사해야 합니다.

디렉토리 생성 시간 설정 및 가져오기

SetCreationTime 및 GetCreationTime 메서드는 지정된 파일의 생성 날짜와 시간을 설정하고 가져오는 데 사용됩니다. 다음 코드 스니펫은 파일의 생성 시간을 설정하고 가져옵니다.

// 파일 생성 시간 가져오기 및 설정하기
string fileName = @"D:\Haro.txt";
File.SetCreationTime(fileName, DateTime.Now);
DateTime dt = File.GetCreationTime(fileName);
Console.WriteLine("파일 생성 시간: {0}", dt.ToString());

파일 마지막 액세스 시간 가져오기 및 설정하기

SetLastAccessTime 및 GetLastAccessTime 메서드는 지정된 파일의 마지막 액세스 날짜와 시간을 설정하고 가져오는 데 사용됩니다. 다음 코드 스니펫은 파일의 마지막 액세스 날짜와 시간을 설정하고 가져옵니다.

// 파일 마지막 액세스 시간 가져오기 및 설정하기
string fileName = @"D:\Haro.txt";
File.SetLastAccessTime(fileName,DateTime.Now);
DateTime dt = File.GetLastAccessTime(fileName);
Console.WriteLine("파일 마지막 액세스 시간: {0}", dt.ToString());

파일 마지막 수정 시간 가져오기 및 설정하기

SetLastWriteTime 및 GetLastWriteTime 메서드는 지정된 파일의 마지막 수정 날짜와 시간을 설정하고 가져오는 데 사용됩니다. 다음 코드 스니펫은 파일의 마지막 수정 날짜와 시간을 설정하고 가져옵니다.

// 파일 마지막 수정 시간 가져오기 및 설정하기
string fileName = @"D:\Haro.txt";
File.SetLastWriteTime(fileName,DateTime.Now);
DateTime dt = File.GetLastWriteTime(fileName);
Console.WriteLine("파일 마지막 수정 시간: {0}", dt.ToString());

디렉토리 열거

Directory.EnumerateDirectories 메서드는 지정된 디렉토리에서 디렉토리 이름의 열거 가능한 컬렉션을 반환합니다.

string root = @"D:\Temp";
// 모든 하위 디렉토리 목록 가져오기
var dirs = from dir in Directory.EnumerateDirectories(root) select dir;
Console.WriteLine("하위 디렉토리: {0}", dirs.Count<string>().ToString());
Console.WriteLine("하위 디렉토리 목록");
foreach (var dir in dirs)
{
    Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));
}
디렉토리 열거
디렉토리 열거

‘open’로 시작하는 모든 하위 디렉토리를 가져오려면 다음 코드를사용합니다.

// 'open'로 시작하는 모든 하위 디렉토리 목록 가져오기
var HaDirs = from dir in Directory.EnumerateDirectories(root, "open*") select dir;
Console.WriteLine("하위 디렉토리: {0}", HaDirs .Count<string>().ToString());
Console.WriteLine("하위 디렉토리 목록");
foreach (var dir in HaDirs )
{
    Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));
}
open 으로 시작하는 파일 열거
open 으로 시작하는 파일 열거

파일 열거

Directory.EnumerateFiles 메서드는 지정된 디렉토리에서 파일 이름의 열거 가능한 컬렉션을 반환합니다.

string root = @"D:\Temp";
// 모든 파일 목록 가져오기
var files = from file in Directory.EnumerateFiles(root) select file;
Console.WriteLine("파일: {0}", files.Count<string>().ToString());
Console.WriteLine("파일 목록");
foreach (var file in files)
{
    Console.WriteLine("{0}", file);
}
모든 파일 목록
모든 파일 목록

디렉토리 생성 시간 설정 및 가져오기

Directory.SetCreationTime 및 Directory.GetCreationTime 메서드는 지정된 디렉토리의 생성 날짜와 시간을 설정하고 가져오는 데 사용됩니다. 다음 코드 스니펫은 디렉토리의 생성 시간을 설정하고 가져옵니다.

string root = @"D:\Temp";
// 생성 시간 가져오기 및 설정하기
Directory.SetCreationTime(root, DateTime.Now);
DateTime creationTime = Directory.GetCreationTime(root);
Console.WriteLine(creationTime);

디렉토리 마지막 액세스 시간 가져오기 및 설정하기

SetLastAccessTime 및 GetLastAccessTime 메서드는 지정된 디렉토리의 마지막 액세스 날짜와 시간을 설정하고 가져오는 데 사용됩니다. 다음 코드 스니펫은 디렉토리의 마지막 액세스 날짜와 시간을 설정하고 가져옵니다.

string root = @"D:\Temp";
// 마지막 액세스 시간 가져오기 및 설정하기
Directory.SetLastAccessTime(root, DateTime.Now);
DateTime lastAccessTime = Directory.GetLastAccessTime(root);
Console.WriteLine(lastAccessTime);

디렉토리 마지막 수정 시간 가져오기 및 설정하기

SetLastWriteTime 및 GetLastWriteTime 메서드는 지정된 디렉토리의 마지막 수정 날짜와 시간을 설정하고 가져오는 데 사용됩니다. 다음 코드 스니펫은 디렉토리의 마지막 수정 날짜와 시간을 설정하고 가져옵니다.

string root = @"D:\Temp";
// 마지막 수정 시간 가져오기 및 설정하기
Directory.SetLastWriteTime(root, DateTime.Now);
DateTime lastWriteTime = Directory.GetLastWriteTime(root);
Console.WriteLine(lastWriteTime);

위 예제 코드블럭

string root = @"D:\MyTestDirectory";
// 생성 시간 가져오기 및 설정하기
Directory.SetCreationTime(root, DateTime.Now);
DateTime creationTime = Directory.GetCreationTime(root);
Console.WriteLine("생성 시간 가져오기 및 설정하기 "+ creationTime);

// 마지막 액세스 시간 가져오기 및 설정하기
Directory.SetLastAccessTime(root, DateTime.Now);
DateTime lastAccessTime = Directory.GetLastAccessTime(root);
Console.WriteLine("마지막 액세스 시간 가져오기 및 설정하기 " + lastAccessTime);

// 마지막 수정 시간 가져오기 및 설정하기
Directory.SetLastWriteTime(root, DateTime.Now);
DateTime lastWriteTime = Directory.GetLastWriteTime(root);
Console.WriteLine("마지막 수정 시간 가져오기 및 설정하기 " + lastWriteTime);
시간 가져오기및 설정
시간 가져오기및 설정

현재 디렉토리 가져오기 및 설정하기

SetCurrentDirectory 메서드는 지정된 디렉토리를 현재 디렉토리로 설정합니다. GetCurrentDirectory 메서드는 현재 디렉토리를 반환합니다.

string root = @"D:\Temp";
Directory.SetCurrentDirectory(root);
Console.WriteLine(Directory.GetCurrentDirectory());

하위 디렉토리 가져오기

Directory 클래스의 GetDirectories 메서드는 디렉토리의 모든 하위 디렉토리를 로드합니다. 모든 하위 디렉토리를 가져오려면 하위 디렉토리를 재귀적으로 읽을 수 있습니다.

public void GetSubDirectories()
{
    string root = @"D:\Temp";
    // 모든 하위 디렉토리 가져오기
    string[] subdirectoryEntries = Directory.GetDirectories(root);
    // 하위 디렉토리를 루프로 확인하여 다른 하위 디렉토리가 있는지 확인합니다.
    foreach (string subdirectory in subdirectoryEntries)
    {
        LoadSubDirs(subdirectory);
    }
}
private void LoadSubDirs(string dir)
{
    Console.WriteLine(dir);
    string[] subdirectoryEntries = Directory.GetDirectories(dir);
    foreach (string subdirectory in subdirectoryEntries)
    {
        LoadSubDirs(subdirectory);
    }
}

디렉토리의 파일 가져오기

GetFiles 메서드는 지정된 디렉토리의 파일 목록을 가져옵니다.

string root = @"D:\Temp";
string[] fileEntries = Directory.GetFiles(root);
foreach (string fileName in fileEntries)
{
    Console.WriteLine(fileName);
}

루트 디렉토리 가져오기

GetRootDirectory 메서드는 지정된 디렉토리의 루트 디렉토리를 반환합니다.

string root = @"D:\Temp";
Console.WriteLine(Directory.GetDirectoryRoot(root));

모든 드라이브 가져오기

GetLogicalDrives 메서드는 시스템의 모든 논리 드라이브를 반환합니다.

string[] drives = System.IO.Directory.GetLogicalDrives();
foreach (string drive in drives)
{
    System.Console.WriteLine(drive);
}

결론

이 포스트에서는 C# Directory 클래스를 사용하여 C#에서 폴더와 파일을 생성하고 액세스하는 방법을 알려드렸습니다.

Leave a Comment