System.IO.Directory.Delete目录删除

在程序运行的时候,如果直接获取一个目录路径,然后执行删除(包括子目录及文件):

System.IO.Directory.Delete(path,true);

或者

System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(path);
downloadedMessageInfo.Delete(true);

如果手动在目录里面复制一个文件然后再粘贴一个副本相当于添加文件或者目录(而不是删除)就会报错:

{System.IO.IOException: 目录不是空的。

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
at System.IO.DirectoryInfo.Delete(Boolean recursive)

 这样的错误只有在svn的目录里面才能出现,不知道为什么

 

 

System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(dirPath);
foreach (FileInfo file in downloadedMessageInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
{
dir.Delete(true);
}

 

也可以使用DirectoryInfo 扩展方法:

public static class DirectoryExtensions
    {

        public static void Empty(this System.IO.DirectoryInfo directory)
        {
            foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
            foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
        }
    }

 

posted @ 2013-11-21 14:10  亲福  阅读(5746)  评论(0编辑  收藏  举报