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.
The double backslash is the normal way to represent a backslash in a string. When you use @ you are saying that you don't want to interpret any escape sequence (among other things, see here for more info, under "Literals")
So the problem is different. Do C:\test1.txt and C:\Test exist? Do you have permission to write in targetPath?
Try the following (add exception handling and more error checking as needed)
if (!Directory.Exists(targetPath)) {
Directory.CreateDirectory(targetPath);
}
if (File.Exists(sourceFile)) {
File.Copy(sourceFile,destFile,true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With