-1

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

这是我使用的代码:

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 来将目标中不存在的文件从源复制到目标吗?

4

3 回答 3

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方法)。

于 2013-08-28T15:53:38.727 回答
3

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

改用:

File.Copy(Path.Combine(strSrcPath , strFile ), Path.Combine(strDstPath, strFile);
于 2013-08-28T15:56:58.500 回答
2

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

所以

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

将在哪里失败

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

将不会

于 2013-08-28T15:56:30.600 回答