728x90
DirectoryInfo
is a class in the System.IO
namespace that provides instance methods for creating, moving, and enumerating through directories and subdirectories. It's similar to the Directory
class but works with specific directory instances, allowing more detailed and advanced operations.
Key Properties:
- Name: Gets the name of the directory.
- FullName: Gets the full path of the directory.
- Parent: Gets the parent directory of a specified subdirectory.
- CreationTime: Gets or sets the creation time of the directory.
- LastAccessTime: Gets or sets the last access time of the directory.
- LastWriteTime: Gets or sets the last write time of the directory.
Common Methods:
Create:
// Creates the directory DirectoryInfo dirInfo = new DirectoryInfo(@"C:\ExampleDirectory"); dirInfo.Create();
Delete:
// Deletes the directory dirInfo.Delete(true); // 'true' means delete recursively
Exists:
// Checks if the directory exists if (dirInfo.Exists) { Console.WriteLine("Directory exists."); } else { Console.WriteLine("Directory does not exist."); }
GetFiles:
// Gets the files in the directory FileInfo[] files = dirInfo.GetFiles(); foreach (FileInfo file in files) { Console.WriteLine(file.Name); }
GetDirectories:
// Gets the subdirectories in the directory DirectoryInfo[] directories = dirInfo.GetDirectories(); foreach (DirectoryInfo directory in directories) { Console.WriteLine(directory.Name); }
MoveTo:
// Moves the directory to a new location dirInfo.MoveTo(@"C:\NewExampleDirectory");
Example Usage:
Here’s an example demonstrating some of these properties and methods:
using System;
using System.IO;
class Program
{
static void Main()
{
DirectoryInfo dirInfo = new DirectoryInfo(@"C:\ExampleDirectory");
// Create the directory
dirInfo.Create();
Console.WriteLine("Directory created at: " + dirInfo.FullName);
// Check if the directory exists
if (dirInfo.Exists)
{
Console.WriteLine("The directory exists.");
// List files in the directory
FileInfo[] files = dirInfo.GetFiles();
Console.WriteLine("Files:");
foreach (FileInfo file in files)
{
Console.WriteLine(file.Name);
}
// List subdirectories in the directory
DirectoryInfo[] subdirectories = dirInfo.GetDirectories();
Console.WriteLine("Subdirectories:");
foreach (DirectoryInfo subdirectory in subdirectories)
{
Console.WriteLine(subdirectory.Name);
}
}
// Move the directory to a new location
string newDirectoryPath = @"C:\NewExampleDirectory";
dirInfo.MoveTo(newDirectoryPath);
Console.WriteLine("Directory moved to: " + newDirectoryPath);
// Delete the directory
dirInfo = new DirectoryInfo(newDirectoryPath); // Update dirInfo to the new path
dirInfo.Delete(true);
Console.WriteLine("Directory deleted.");
}
}
728x90
반응형
'Software > C#' 카테고리의 다른 글
C# DevExpress - WinForm GridControl Header 90회전 (1) | 2025.01.20 |
---|---|
C# 시작하기 - Namespace : System (0) | 2025.01.11 |
C# 시작하기 - FileInfo (0) | 2025.01.11 |
C# 시작하기 - System.IO (0) | 2025.01.11 |
C# 시작하기 - System.IO.Directory (0) | 2025.01.11 |