System.IO.DirectoryInfo.Delete 方法 (Boolean)

方法描述

删除 DirectoryInfo 的此实例,指定是否删除子目录和文件。

语法定义(C# System.IO.DirectoryInfo.Delete 方法 (Boolean) 的用法)

public void Delete(
	bool recursive
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
recursive System-Boolean 若为 true,则删除此目录、其子目录以及所有文件;否则为 false。
返回值 void

提示和注释

如果 DirectoryInfo 没有文件或子目录,则即使 recursive 为 false,此方法也会删除 DirectoryInfo。 尝试在 recursive 为 false 时删除不为空的 DirectoryInfo 将引发 IOException。

有关通用 I/O 任务的列表,请参见通用 I/O 任务。

System.IO.DirectoryInfo.Delete 方法 (Boolean)例子

然后取消代码中该行的注释,测试目录是否成功移除。

using System;
using System.IO;

public class DeleteTest 
{
    public static void Main() 
    {

        // Make a reference to a directory.
        DirectoryInfo di = new DirectoryInfo("TempDir");

        // Create the directory only if it does not already exist.
        if (di.Exists == false)
            di.Create();

        // Create a subdirectory in the directory just created.
        DirectoryInfo dis = di.CreateSubdirectory("SubDir");

        // Process that directory as required.
        // ...

        // Delete the subdirectory. The true indicates that if subdirectories
        // or files are in this directory, they are to be deleted as well.
        dis.Delete(true);

        // Delete the directory.
        di.Delete(true);
    }
}

异常

异常 异常描述
UnauthorizedAccessException 目录中包含一个只读文件。
DirectoryNotFoundException 此 DirectoryInfo 对象描述的目录不存在或未能找到。
IOException
  • 目录为只读。
  • 此目录包含一个或多个文件或子目录,且 recursive 为 false。
  • 该目录为应用程序的当前工作目录。
  • 对于目录或其文件之一有打开句柄,并且操作系统是 Windows XP 或更早版本。 此打开句柄可能是由于枚举目录和文件导致的。 有关更多信息,请参见 如何:枚举目录和文件。
SecurityException 调用方没有所要求的权限。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。