File.Move()是内置的File类方法,用于将指定的文件移动到新位置。此方法还提供了指定新文件名的选项。
句法:
public static void Move (string sourceFileName, string destFileName);
参数:该函数接受两个参数,如下所示:
- sourceFileName: This is the specified source file which are going to be moved. It can be absolute or relative path.
- destFileName: This is the specified destination file where source file is going to be moved.
例外情况:
- IOException: destFileName已经存在。
- FileNotFoundException:找不到sourceFileName 。
- ArgumentNullException: sourceFileName或destFileName为null。
- ArgumentException: sourceFileName或destFileName是长度为零的字符串,仅包含空格或InvalidPathChars中定义的无效字符。
- UnauthorizedAccessException:调用者没有所需的权限。
- PathTooLongException:给定的路径,文件名或两者都超过了系统定义的最大长度。
- DirectoryNotFoundException:在sourcefilename或destFileName中指定的路径无效。
- NotSupportedException: sourceFileName或destFileName的格式无效。
下面是说明File.Move()方法的程序。
程序1:在运行下面的代码之前,将创建一个文件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 ,如下所示-
程序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);
}
}
}
运行时错误:
System.IO.FileNotFoundException: Could not find file ‘/home/runner/NutritiousHeavyRegression/file.txt’.
File name: ‘/home/runner/NutritiousHeavyRegression/file.txt’
at System.IO.File.Move (System.String sourceFileName, System.String destFileName) [0x0007c] in :0
at GFG.Main () [0x00000] in :0