📜  C#中的File.Move()方法与示例

📅  最后修改于: 2021-05-29 17:29:14             🧑  作者: Mango

File.Move()是内置的File类方法,用于将指定的文件移动到新位置。此方法还提供了指定新文件名的选项。

句法:

public static void Move (string sourceFileName, string destFileName);

参数:该函数接受两个参数,如下所示:

例外情况:

  • IOException: destFileName已经存在。
  • FileNotFoundException:找不到sourceFileName
  • ArgumentNullException: sourceFileNamedestFileName为null。
  • ArgumentException: sourceFileNamedestFileName是长度为零的字符串,仅包含空格或InvalidPathChars中定义的无效字符。
  • UnauthorizedAccessException:调用者没有所需的权限。
  • PathTooLongException:给定的路径,文件名或两者都超过了系统定义的最大长度。
  • DirectoryNotFoundException:sourcefilenamedestFileName中指定的路径无效。
  • NotSupportedException: sourceFileNamedestFileName的格式无效。

下面是说明File.Move()方法的程序。

程序1:在运行下面的代码之前,将创建一个文件file.txt ,其内容如下所示-

file.txt

// C# program to illustrate the usage
// of File.Move() method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    static void Main()
    {
        try {
            // Moving the file file.txt to location C:\gfg.txt
            File.Move(@"file.txt", @"C:\gfg.txt");
            Console.WriteLine("Moved");
        }
        catch (IOException ex) {
            Console.WriteLine(ex);
        }
    }
}

输出:

Moved

运行上述代码后,将显示以上输出,并将现有文件file.txt移至新位置C:\ gfg.txt ,如下所示-

C:\ gfg.txt

程序2:最初没有创建文件。

// C# program to illustrate the usage
// of File.Move() method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    static void Main()
    {
        try {
            // If file.txt is not found
            // then an exception will be shown
            File.Move(@"file.txt", @"C:\gfg.txt");
            Console.WriteLine("Moved");
        }
        catch (IOException ex) {
            Console.WriteLine(ex);
        }
    }
}

运行时错误: