日期:2014-05-18 浏览次数:21165 次
using System; using System.Collections; using System.Windows.Forms; using System.IO; namespace DYBC { public class FileExec { public FileExec() { } private static void CopyDirectory(DirectoryInfo OldDirectory, DirectoryInfo NewDirectory) { string NewDirectoryFullName = NewDirectory.FullName + @"\" + OldDirectory.Name; if ( !Directory.Exists(NewDirectoryFullName) ) Directory.CreateDirectory(NewDirectoryFullName); FileInfo[] OldFileAry = OldDirectory.GetFiles(); foreach (FileInfo aFile in OldFileAry) File.Copy(aFile.FullName, NewDirectoryFullName + @"\" + aFile.Name, true); DirectoryInfo[] OldDirectoryAry = OldDirectory.GetDirectories(); foreach ( DirectoryInfo aOldDirectory in OldDirectoryAry ) { DirectoryInfo aNewDirectory = new DirectoryInfo(NewDirectoryFullName); CopyDirectory(aOldDirectory, aNewDirectory); } } //CopyDirectory public static void CopyDirectory(string OldDirectoryStr, string NewDirectoryStr) { DirectoryInfo OldDirectory = new DirectoryInfo( OldDirectoryStr ); DirectoryInfo NewDirectory = new DirectoryInfo( NewDirectoryStr ); FileExec.CopyDirectory(OldDirectory,NewDirectory); } //DelDirectory public static void DelDirectory(string OldDirectoryStr) { DirectoryInfo OldDirectory = new DirectoryInfo( OldDirectoryStr ); OldDirectory.Delete(true); } //CopyDirectory And DelDirectory public static void CopyAndDelDirectory(string OldDirectory, string NewDirectory) { CopyDirectory( OldDirectory,NewDirectory); DelDirectory( OldDirectory ); } } }
------解决方案--------------------
用递归法删除.
DirectoryInfo dir = new DirectoryInfo(path);
DirectoryInfo[] childADir=dir.GetDirectories();
FileInfo[] childAFiles = dir.GetFiles();
if (childAFiles.Length > 0)
{
for (int j = 0; j < childAFiles.Length; j++)
{
string newFilePath = path + @"\" + childAFiles[j].Name.ToString();
File.Delete(newFilePath);
}
}
if (childADir.Length > 0)
{
for (int i = 0; i < childADir.Length; i++)
{
string newPath = path + @"\" + childADir[i].Name.ToString();
DelDir(newPath);
}
}