System.IO.DirectoryInfo.MoveTo 方法

方法描述

将 DirectoryInfo 实例及其内容移动到新路径。

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

public void MoveTo(
	string destDirName
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
destDirName System-String 要将此目录移动到的目标位置的名称和路径。目标不能是另一个具有相同名称的磁盘卷或目录。它可以是您要将此目录作为子目录添加到其中的一个现有目录。
返回值 void

提示和注释

例如,如果尝试将 c:\mydir 移动到 c:\public,而 c:\public 已经存在,则此方法将引发 IOException。 您必须将“c:\\public\\mydir”指定为 destDirName 参数,或者指定新目录名,例如“c:\\newdir”。

此方法允许将一个目录移到只读目录。 两个目录的读/写特性都不会受到影响。

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

System.IO.DirectoryInfo.MoveTo 方法例子

下面的示例演示如何移动目录。

using System;
using System.IO;

public class MoveToTest 
{
    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");

        // Move the main directory. Note that the contents move with the directory.
        if (Directory.Exists("NewTempDir") == false)
            di.MoveTo("NewTempDir");

        try 
        {
            // Attempt to delete the subdirectory. Note that because it has been
            // moved, an exception is thrown.
            dis.Delete(true);
        } 
        catch (Exception) 
        {
            // Handle this exception in some way, such as with the following code:
            // Console.WriteLine("That directory does not exist.");
        }

        // Point the DirectoryInfo reference to the new directory.
        //di = new DirectoryInfo("NewTempDir");

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

异常

异常 异常描述
ArgumentNullException destDirName 为 null。
ArgumentException destDirName 是空字符串 ("")。
IOException
  • 尝试将一个目录移到不同的卷。
  • destDirName 已存在。
  • 您无权访问此路径。
  • 被移动的目录与目标目录同名。
SecurityException 调用方没有所要求的权限。
DirectoryNotFoundException 找不到此目标目录。

命名空间

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 系统要求。