new to C# - unable to get File.Copy to work

MariusD picture MariusD · Apr 10, 2012 · Viewed 13.3k times · Source

This is a code sample from Microsoft, with a different file location, that just won't work:

 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);

It can't find the source file. If I set a break point, this is what I get:

    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

So it looks like it is doubling the backslashes even though a verbatim string is used. (there is no doubt that I have a test1.txt file in C:) Any ideas? Thanks!

Answer

David Heffernan picture David Heffernan · Apr 10, 2012

There are 3 common failure modes:

  1. The source file C:\test1.txt does not exist.
  2. The destination file C:\Test\test1.txt exists but is read-only.
  3. The destination directory C:\Test does not exist.

My guess is that item 3 is the problem and if so you need to make sure that the destination directory exists before you call File.Copy. If this is the case you will be seeing a DirectoryNotFoundException. You can use Directory.CreateDirectory to make sure the destination directory exists.