Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 989
MariusD Avatar asked Dec 28 '22 02:12

MariusD


2 Answers

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.

like image 72
David Heffernan Avatar answered Dec 30 '22 10:12

David Heffernan


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);
}
like image 37
Vinko Vrsalovic Avatar answered Dec 30 '22 09:12

Vinko Vrsalovic