C#的新手 - 无法让File.Copy工作

Mar*_*usD 2 c# string verbatim

这是Microsoft的代码示例,具有不同的文件位置,但不起作用:

 string fileName = "test1.txt";
 string sourcePath = @"C:\";
 string targetPath = @"C:\Test\";

 // Use Path class to manipulate file and directory paths.
 string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
 string destFile = System.IO.Path.Combine(targetPath, fileName);

 System.IO.File.Copy(sourceFile, destFile, true);
Run Code Online (Sandbox Code Playgroud)

它找不到源文件.如果我设置了一个断点,这就是我得到的:

    args    {string[0]} string[]
    fileName    "test1.txt" string
    sourcePath  "C:\\"  string
    targetPath  "C:\\Test\\"    string
    sourceFile  "C:\\test1.txt" string
    destFile    "C:\\Test\\test1.txt"   string
Run Code Online (Sandbox Code Playgroud)

因此,即使使用逐字字符串,它看起来也会加倍反斜杠.(毫无疑问,我在C中有一个test1.txt文件:)有什么想法吗?谢谢!

Dav*_*nan 5

有3种常见的故障模式:

  1. 源文件C:\test1.txt不存在.
  2. 目标文件C:\Test\test1.txt存在但是只读.
  3. 目标目录C:\Test不存在.

我的猜测是第3项是问题,如果是这样,你需要在调用之前确保目标目录存在File.Copy.如果是这种情况,你会看到一个DirectoryNotFoundException.您可以使用Directory.CreateDirectory以确保目标目录存在.