Sunday, April 17, 2011

move zip file using file.copy()

I am trying to move a file from server \\abc\\C$\\temp\\coll.zip to another server \\def\\c$\\temp.

I am trying to use File.Copy(source,destination). But I am getting the error in source path saying: Couldn't find the part of the path.

I am not sure what is wrong with the source path.

From stackoverflow
  • looks like you need two backslashes at the beginning:

    • \\abc\C$\temp\coll.zip
    • \\def\c$\temp
  • Make sure that your "\" characters are escaped if you are using C#. You have to double the backslashes or prefix the string literal with @, like this:

    string fileName = @"\\abc\C$\temp\coll.zip";

    or

    string fileName = "\\\\abc\\C$\\temp\\coll.zip";

    Jon Skeet : I strongly suspect that the first backslash should be doubled, e.g. @"\\abc\C$\..."
    0xA3 : Right Jon, it was removed when someone reformatted the post.
    Michael Meadows : There's some funky escaping going on in the SO editer.
  • It could be the string you are using for the path. If it is exactly as you have entered here I believe you need double backslashes. "\\" before the server name.

  • I always use network shares for that kind of work, but UNC path's should be available too.

    Don't forget that you need to escape your string when you use \'s. Also, UNC paths most of the time start with a double .

    Example:

    \\MyComputerName\C$\temp\temp.zip
    
  • Actually I missed @ before the two strings.The source and the destination path. That is why it was giving error.

  • Make sure you are using a valid UNC Path. UNC paths should start with \ not just . You should also consider using System.IO.File.Exists(filename); before attempting the copy so you can avoid the exception altogether and so your app can handle the missing file gracefully.

    Hope this helps

  • You could use a C# @ Verbatim and also use checks in the code like this:

    string source = @"\\abc\C$\temp\coll.zip";
    string destination = @"\\def\c$\temp\coll.zip";
    string destDirectory = Path.GetDirectoryName(destination)
    if (File.Exists(source) && Directory.Exists(destDirectory)) {
        File.Copy(source, destination);
    }
    else {
        // Throw error or alert
    }
    
    Mitchel Sellers : This wouldn't be valid if the file didn't already exist on the target location. You would need to use Directory.Exists(destination) to validate.
    Seb Nilsson : I was a bit quick, thanks for pointing that out.

0 comments:

Post a Comment