Problem:
A root folder contains multi-level directories. Multiple subfolders exist at each level, and multiple files exist in each folder.
If you want to delete all the sub-files and save the top-level directory folder, how can this problem be solved?
Solution
1. Delete the root folder and create a root folder.
Void deleteallfile (string path)
{
Directory. Delete (path, true );
Directory. createdirectory (PATH );
}
2. traverse the files in all subdirectories and delete them one by one.
/// <Summary>
/// Traverse all files in folders and subfolders
/// </Summaryd>
/// <C> string dir = listfiles (New directoryinfo (DIR); </C>
/// <Param name = "filedirectory"> folder directory path </param>
/// <Returns> returns the arraylist object </returns>
Public static system. Collections. arraylist listfiles (string filedirectory)
{
Arraylist arylist = NULL;
If (directory. exists (filedirectory ))
{
Directoryinfo dinfo = new directoryinfo (filedirectory );
If (dinfo! = NULL)
{
Filesysteminfo [] files = dinfo. getfilesysteminfos ();
For (INT I = 0; I <files. length; I ++)
{
Fileinfo file = files [I] As fileinfo;
If (file! = NULL)
{
If (arylist = NULL)
Arylist = new arraylist ();
Arylist. Add (File );
}
Else
{
Listfiles (files [I]. fullname); // recursively calls sub-directories.
}
}
}
}
Return arylist;
}
The first method is the most direct, does not require recursion, and does not require traversal. However, the system method is called and the internal principle is unknown.
In general, the first method is better than the second method! To be further verified.
You can use the following method to delete all files in a folder.
Void deleteallfile (string path)
{
Foreach (string dirstr in directory. getdirectories (PATH ))
{
Directoryinfo dir = new directoryinfo (dirstr );
}
Arraylist folders = new arraylist ();
Filesysteminfo [] filearr = dir. getfilesysteminfos ();
For (INT I = 0; I <folders. Count; I ++)
{
Fileinfo F = folders [I] As fileinfo;
If (F = NULL)
{
Directoryinfo d = folders [I] As directoryinfo;
D. Delete ();
}
}
}