17.2.1 Directory Management
. The NET Framework structure provides us with directory classes for catalog management in the namespace System.IO. With it, we can create, move, browse, and even define a hidden directory and a read-only directory for the directory and its subdirectories.
The form of the directory's constructors is as follows:
Public Directory (string path);
Where the parameter path represents the path where the directory resides.
The main properties of the directory are:
ATTRIBUTES:0X01 represents a read-only, 0x02 represents a hidden.
Name: the current pathname.
Parent: The first-level name of the directory.
Root: The name of the root directory.
Creation time: Directory creation times.
LastAccessTime: The last time the directory was accessed.
LastWriteTime: Last time the directory was modified.
Some of the member methods that we use for directory classes are:
CreateDirectory (string path): subdirectories are created.
Createdirectories (String path): Create multilevel subdirectories.
CreateFile (string filename): Creates a new file under the current directory.
Delete (): Deletes a directory.
In the following example, we use the directory's CreateDirectory and Createdirectories methods to create level I and level two directories.
Program Listing 17-1:
Using System;
Using System.IO;
Class Directorytest
{public
static void Main ()
{
directory d=new directory ("c:\\c#");
Directory D1;
Directory D2;
try{
d1=d.createsubdirectory ("File1");
}
catch (IOException e)
{
Console.WriteLine ("Directory File1 failed Because:{0}", e);
return;
}
try{
d2=d.createsubdirectories ("File1\\file2");
Equals D2=d1. Createsubdirectory ("File2");
}
catch (IOException e)
{
Console.WriteLine ("Directory File2 failed Because:{0}", e);
return;
}
Console.WriteLine ("Create directory successfully!");
}
The exception IOException in the example above indicates that the directory name that is being created already exists. System.IO provides a variety of input and output exceptions that allow us to understand why a task failed, or to give a user a message to the program.
Similarly, we can do directory deletion operations.
Program Listing 17-2:
using System; using System.IO; class Directorytest {public static void Main () {Directory d=new directory ("c:\\
C#file1 ");
Directory[] SubDir;
try{subdir=d.getdirectories ();
catch (DirectoryNotFoundException e) {Console.WriteLine ("Can not find such a directory because:{0}", E);
Return foreach (Directory dir in subdir) {dir.
Delete ();
} d.delete ();
Console.WriteLine ("Delete successfully!"); }}