文件复制与另一种选择?

时间:2013-08-28 15:52:25

标签: c#

我想将文件复制到目录中。我认为这将是一个简单的过程。

这是我使用的代码:

string strSrcPath = "C:\Users\Documents\Development\source\11.0.25.10\",
strDstPath = "C:\Users\Documents\Development\testing\11.0.25.10\",
strFile = "BuildLog.txt"

File.Copy(Path.Combine(sourcePath, sourceFile), strDstPath);

这里的问题是,当我在做File.Copy时,它想要将一个文件复制到另一个文件,但我不想这样做,因为目标路径中不存在该文件。因此,我得到一个错误,其中包含“无法复制,strDstPath是目的地而不是文件”的内容。

我可以用一些东西而不是File.Copy来复制目标中不存在的文件从源到目的地吗?

3 个答案:

答案 0 :(得分:3)

您似乎将一些错误的参数传递给Path.Combine(第二个)。它应该是strFile而不是sourceFile,目前还不清楚它来自哪里。

您还需要为目标文件夹提供文件名:

File.Copy(Path.Combine(sourcePath, strFile), Path.Combine(strDstPath, strFile));

您还需要转义字符串中的\字符,因为您的代码可能无法编译。这可以通过使用\\或在字符串开头使用@字符来完成。

string strSrcPath = @"C:\Users\Documents\Development\source\11.0.25.10\",
strDstPath = @"C:\Users\Documents\Development\testing\11.0.25.10\",
strFile = "BuildLog.txt"

File.Copy(Path.Combine(sourcePath, strFile), Path.Combine(strDstPath, strFile));

还要确保您指定的目标文件夹存在。如果它不存在,您需要先创建它(使用Directory.CreateDirectory方法)。

答案 1 :(得分:3)

问题是参数是源文件名和目标文件名。您正在传递目标目录,并且程序很困惑,因为您无法将该文件放入目录。

改为使用:

File.Copy(Path.Combine(strSrcPath , strFile ), Path.Combine(strDstPath, strFile);

答案 2 :(得分:2)

您必须为目的地指定文件名

所以

File.Copy("XMLFile1.xml", @"c:\temp");

将失败

File.Copy("XMLFile1.xml", @"c:\temp\XMLFile1.xml");

不会