4

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!

Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
MariusD
  • 129
  • 1
  • 2
  • 14
  • 3
    What's the exception message and stack trace? – SLaks Apr 10 '12 at 14:13
  • 3
    The doubling of the backslashes is just for display. What error message do you receive. – David Heffernan Apr 10 '12 at 14:13
  • Could you please post the exception text? The double backslashes are fine. – Matten Apr 10 '12 at 14:14
  • It isn't actually a double back slash - it just appears like that during debugging. A pain the arse I know. – SkonJeet Apr 10 '12 at 14:15
  • It's most likely that the directory C:\Test does not exist. – Matten Apr 10 '12 at 14:15
  • 1
    Are you certain `test1.txt` exists on the root of the C drive? Does the account used to run the application have the right permissions to copy the file? Is the file in use (i.e. opened in an editor somewhere)? – Oded Apr 10 '12 at 14:16
  • My guess is that the directory c:\Test does not exist. You need to check if that directory exists first exists in code and if not, create the directory before copying. – mbx-mbx Apr 10 '12 at 14:18
  • Thank you, everybody, levanlevi was right, due to "hide known file extensions" being set for the machine, the actual file name was test1.txt.txt... something I will certainly remember!!!!! – MariusD Apr 10 '12 at 14:46

5 Answers5

8

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
4

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);
}
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • 1
    Surely this is a comment, not an answer!? – SkonJeet Apr 10 '12 at 14:16
  • It has the same suggestions as the top voted answer... and clarifies the double backslash in greater detail – Vinko Vrsalovic Apr 10 '12 at 14:17
  • David Heffernan has covered all possible causes for the problem - you're requesting further information from the OP in order to do so - and failed to mention the possibility that this could be an access issue. Everyone else in the comments of the OP have covered all that you have in your 'answer' but have no chance of gaining the rep for being marked as correct. Doesn't seem fair. – SkonJeet Apr 10 '12 at 14:19
  • I was trying to use the Socratic method to illuminate the OP, the answers were not required. And none of the comments explained the Literal string and escaping completely. And that's that. If you find that unfair, sorry, not my intention. – Vinko Vrsalovic Apr 10 '12 at 14:28
  • In that case, Socrates proposed method of solving the OPs problem could have quite easily been exercised in the comments as opposed to an answer. Apology accepted anyway - well edited. – SkonJeet Apr 10 '12 at 14:29
  • The backslash confusion didn't lend itself well to the socratic method. – Vinko Vrsalovic Apr 10 '12 at 14:33
0

If you are having trouble try and look at this example:

using System;
using System.IO;
class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = path + "temp";

        try 
        {
            // Create the file and clean up handles.
            using (FileStream fs = File.Create(path)) {}

            // Ensure that the target does not exist.
            File.Delete(path2);

            // Copy the file.
            File.Copy(path, path2);
            Console.WriteLine("{0} copied to {1}", path, path2);

            // Try to copy the same file again, which should succeed.
            File.Copy(path, path2, true);
            Console.WriteLine("The second Copy operation succeeded, which was expected.");
        } 

        catch 
        {
            Console.WriteLine("Double copy is not allowed, which was not expected.");
        }
    }
}

Taken from : http://msdn.microsoft.com/en-us/library/system.io.file.copy(v=vs.71).aspx

Dhruv Arya
  • 95
  • 1
  • 12
0

doubling of backslashes is correct, I think your problem is file name. try to read the file without that operations, but before see if you "Hide Extenstions for known Type" if you do than filename should be test1.txt.txt :)

levi
  • 3,451
  • 6
  • 50
  • 86
0

To see exactly what goes wrong, you could wrap the code in a try-catch block:

try { // Code that can throw an exception }
catch (Exception ex)
{
    // Show what went wrong
    // Use Console.Write() if you are using a console
    MessageBox.Show(ex.Message, "Error!");
}

The most likely problems are a missing source file, destination folder doesn't exist, or you don't have permission to access that location.

On windows 7 I noticed that you need administrator privileges to write directly to the root of the drive where the operating system is installed (usually c:\). Trying to write a file, or create a directory in that location will probably fail, so I suggest you use another location.

Tibi
  • 4,015
  • 8
  • 40
  • 64