📜  如何在 C# 中复制文件(1)

📅  最后修改于: 2023-12-03 14:52:14.706000             🧑  作者: Mango

如何在 C# 中复制文件

在 C# 中,我们可以使用 System.IO.File 类提供的 Copy 方法来进行文件复制。下面是一个简单的示例:

using System.IO;

// 复制文件
File.Copy("sourceFile.txt", "destinationFile.txt");

上述代码将会把名为 sourceFile.txt 的文件复制到名为 destinationFile.txt 的文件。

如果目标文件已经存在,Copy 方法会抛出 System.IO.IOException 异常。为了避免这种情况,我们可以增加一个布尔型参数 overwrite,设置为 true 时,会覆盖目标文件;设置为 false 时,会抛出异常。

using System.IO;

// 复制文件,覆盖目标文件
File.Copy("sourceFile.txt", "destinationFile.txt", true);

// 复制文件,不覆盖目标文件
File.Copy("sourceFile.txt", "destinationFile.txt", false);

常见的错误之一是在复制文件时没有正确地处理文件路径。可以使用 Path.Combine 方法来处理文件路径,以避免这种错误。

using System.IO;

// 处理文件路径
string sourcePath = Path.Combine("C:", "sourceFolder", "sourcefile.txt");
string destinationPath = Path.Combine("C:", "destinationFolder", "destinationFile.txt");

// 复制文件
File.Copy(sourcePath, destinationPath);

总之,在 C# 中复制文件非常简单。只需使用 System.IO.File 类,并参考上述示例代码即可。