📜  移动文件 c# (1)

📅  最后修改于: 2023-12-03 15:27:20.568000             🧑  作者: Mango

移动文件 C#

在 C# 中,我们可以使用 System.IO 命名空间提供的 File 类和 Directory 类来移动文件和文件夹。

移动文件

可以使用 File 类的 Move 方法来移动文件。该方法需要两个参数,第一个参数是要移动的文件的路径和名称,第二个参数是移动后文件的新路径和名称。

string sourceFilePath = @"C:\Users\username\Desktop\example.txt";
string targetFilePath = @"C:\Users\username\Documents\example.txt";

File.Move(sourceFilePath, targetFilePath);

在上面的示例中,我们将示例文件 example.txt 从桌面移动到文档目录。请注意,如果目标路径中已经有同名文件,则会替换该文件。

移动文件夹

可以使用 Directory 类的 Move 方法来移动文件夹。该方法需要两个参数,第一个参数是要移动的文件夹的路径和名称,第二个参数是移动后文件夹的新路径和名称。

string sourceFolderPath = @"C:\Users\username\Desktop\example_folder";
string targetFolderPath = @"C:\Users\username\Documents\example_folder";

Directory.Move(sourceFolderPath, targetFolderPath);

在上面的示例中,我们将示例文件夹 example_folder 从桌面移动到文档目录。请注意,如果目标路径中已经有同名文件夹,则会替换该文件夹。

错误处理

在移动文件和文件夹时,可能会发生错误,例如源文件不存在或目标路径无效。我们可以使用 try-catch 块来处理这些错误,并提供适当的错误消息给用户。

try
{
    File.Move(sourceFilePath, targetFilePath);
    Directory.Move(sourceFolderPath, targetFolderPath);
}
catch (FileNotFoundException)
{
    Console.WriteLine("源文件不存在。");
}
catch (DirectoryNotFoundException)
{
    Console.WriteLine("源文件夹不存在。");
}
catch (IOException ex)
{
    Console.WriteLine($"移动文件或文件夹时出现错误:{ex.Message}");
}

在上面的示例中,我们使用 try-catch 块来处理 FileNotFoundException、DirectoryNotFoundException 和 IOException 异常。我们可以根据需要添加其他异常处理程序。

以上就是在 C# 中移动文件和文件夹的介绍。希望对您有所帮助!