如何将文件复制到另一个路径?

mrb*_*lah 48 c# file-io

我需要将文件复制到另一个路径,将原始文件保留在原来的位置.

我还希望能够重命名该文件.

FileInfo的CopyTo方法会起作用吗?

Adr*_*der 80

看看File.Copy()

使用File.Copy,您可以将新文件名指定为目标字符串的一部分.

所以像

File.Copy(@"c:\test.txt", @"c:\test\foo.txt");
Run Code Online (Sandbox Code Playgroud)

另请参见如何:复制,删除和移动文件和文件夹(C#编程指南)

  • 需要注意的一件重要事情是,您可以通过将第三个参数添加为true或false来指定是否必须覆盖目标文件. (2认同)

Saj*_*ood 7

我试图将xml文件从一个位置复制到另一个位置.这是我的代码:

public void SaveStockInfoToAnotherFile()
{
    string sourcePath = @"C:\inetpub\wwwroot";
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
    string sourceFileName = "startingStock.xml";
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);

    if (!System.IO.Directory.Exists(destinationPath))
       {
         System.IO.Directory.CreateDirectory(destinationPath);
       }
    System.IO.File.Copy(sourceFile, destinationFile, true);
}
Run Code Online (Sandbox Code Playgroud)

然后我在一定间隔的timer_elapsed函数中调用了这个函数,我认为你不需要看.有效.希望这可以帮助.


Rub*_*ias 6

是.它将工作:FileInfo.CopyTo方法

使用此方法允许或阻止覆盖现有文件.使用CopyTo方法可以防止默认情况下覆盖现有文件.

所有其他答案都是正确的,但既然你要求FileInfo,这里是一个样本:

FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten
Run Code Online (Sandbox Code Playgroud)