c#删除文件夹(目录)

来源:互联网 发布:阿里云北京机房地址 编辑:程序博客网 时间:2024/06/10 01:43

在用Directory.Delete删除文件夹时,报“目录不是空的。"异常。

如果要删除的文件夹下还有文件夹或者文件,就会报目录不是空的的异常,如何删除文件夹以及文件夹内的所有文件夹和文件呢?

解决办法1

System.IO.Directory.Delete(@"C:/Temp", true); 就可以删除了////注意C:/Temp后面没有/

Directory.Delete (String, Boolean)

 

作用:删除指定的目录并(如果指示)删除该目录中的任何子目录。

 

解决办法2

使用递归方法:下面给出两种使用递归删除目录的代码

public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件   
                }
                else
                    DeleteFolder(d);//递归删除子文件夹   
            }
            Directory.Delete(dir);//删除已空文件夹   
        }


        private void DeleteDir(string path)
        {
            if (path.Trim() == "" || !Directory.Exists(path))
                return;
            DirectoryInfo dirInfo = new DirectoryInfo(path);

            FileInfo[] fileInfos = dirInfo.GetFiles();
            if (fileInfos != null && fileInfos.Length > 0)
            {
                foreach (FileInfo fileInfo in fileInfos)
                {
                    //DateTime.Compare( fileInfo.LastWriteTime,DateTime.Now);
                    File.Delete(fileInfo.FullName); //删除文件
                }
            }

            DirectoryInfo[] dirInfos = dirInfo.GetDirectories();
            if (dirInfos != null && dirInfos.Length > 0)
            {
                foreach (DirectoryInfo childDirInfo in dirInfos)
                {
                    this.DeleteDir(childDirInfo.FullName); //递归
                }
            }
            Directory.Delete(dirInfo.FullName, true); //删除目录
        }

<h4 class="subHeading" style="margin: 0px; padding: 0px;">参数</h4><dl><dt><span class="parameter">path</span></dt><dd><p>要移除的目录的名称。</p></dd></dl><dl><dt><span class="parameter">recursive</span></dt><dd><p>若要移除 <span class="parameter">path</span> 中的目录、子目录和文件,则为 <strong>true</strong>;否则为 <strong>false</strong>。</p><p> </p></dd></dl>

<span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: blue;">void</span> Delete (    <span style="color: blue;">string</span> path,    <span style="color: blue;">bool</span> recursive)
<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14.44444465637207px; line-height: 25.98958396911621px;">转自:</span><a target=_blank href="http://www.itpuji.net.cn/course/show3.php?id=689" style="color: rgb(51, 102, 153); text-decoration: none; font-family: Arial; font-size: 14.44444465637207px; line-height: 25.98958396911621px;">http://www.itpuji.net.cn/course/show3.php?id=689</a>
0 0
原创粉丝点击