C# tips and tricks 29 – DirectoryInfo class | How to Create, Copy, Move, Rename & delete a directory

2
9



What is DirectoryInfo class?
Exposes instance methods for creating, moving and enumerating through directories and subdirectory.
It is sealed class so we cannot inherited.
DirectoryInfo class Provides Methods and Properties.

DirectoryInfo Parent class and namespace
DirectoryInfo class is a System.IO namespace.
DirectoryInfo’s Parent class is a FileSystemInfo.

DirectoryInfo class Properties
Attributes
CreationTime
CreationTimeUtc
Exists
Extension
FullName
LastAccessTime
LastAccessTimeUtc
LastWriteTime
LastWriteTimeUtc
Name
Parent
Root

DirectoryInfo class Methods
Create()
CreateSubdirectory()
Delete()
EnumerateDirectories()
EnumerateFiles()
GetAccessControl()
GetDirectories()
GetFiles()
GetFileSystemInfos()
GetLifetimeService()
InitializeLifetimeService()
MoveTo(String)
Refresh()

Directory info class demo code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace DirectoryInfoDemo
{
class Program
{
static void Main(string[] args)
{
//Create Method
String path = @”E:/Create”;
DirectoryInfo fl = new DirectoryInfo(path);
fl.Create();
Console.WriteLine(“Directory has been created”);

//CreateSubdirectory Method
String path = @”E:/Create”;
DirectoryInfo f1 = new DirectoryInfo(path);
DirectoryInfo dis = f1.CreateSubdirectory(“Subdirectory”);
Console.WriteLine(“Directory has been created”);

//move to method
String path = @”E:/Create”;
string path1 = @”E:/movedirectory/create”;
DirectoryInfo f1 = new DirectoryInfo(path);
DirectoryInfo f2 = new DirectoryInfo(path1);
f1.MoveTo(path1);
Console.WriteLine(“Directory is Moved”);

//delete method
string path = @”E:Create”;
DirectoryInfo fl = new DirectoryInfo(path);
fl.Delete();
Console.WriteLine(“Directory is deleted”);

//GetDirectories Method

try
{
DirectoryInfo di = new DirectoryInfo(@”E:movedirectory”);
DirectoryInfo[] dir1 = di.GetDirectories();
Console.WriteLine(“The number of directories containing is {0} ” , dir1.Length);
}
catch(Exception e)
{
Console.WriteLine(“The process failed: {0}”, e.ToString());
}

DirectoryInfo fi = new DirectoryInfo(@”E:Create”);
Console.WriteLine(“Directory name is {0}”, fi.Name);
Console.WriteLine(“Directory Creation Time is {0}”, fi.CreationTime);
Console.WriteLine(“Directory LastAccess Time is {0}”, fi.LastAccessTime);
Console.WriteLine(“Directory LastWrite Time is {0}”, fi.LastWriteTime);

}
}
}

Nguồn:https://wijstaanvooronzegrondrechten.org/

2 COMMENTS

  1. I think you should do it in windowsform Application, it's gonna be more pretty good to look, and usefull!

LEAVE A REPLY

Please enter your comment!
Please enter your name here