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!
There are 3 common failure modes:
C:\test1.txt
does not exist.C:\Test\test1.txt
exists but is read-only.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.