2

I am trying to copy a file between two UNC paths to which I have full access. The root of each UNC is a different physical drive. I can use file explorer to copy the file with no problem.

string file1 = @"\\node\disk1\dir\file.jpg";
string file2 = @"\\node\disk2\dir\file.jpg";
File.Copy(file1,file2);

The above fails with a DirectoryNotFoundException.

However - this works fine, but it is too slow to be usable and indicates that it is not a permission issue.

Image img = Image.FromFile(file1);
img.Save(file2);

If the files are on the same physical device \node\disk1 then the File.Copy works fine.

RichardB
  • 31
  • 4
  • The 2nd solution will also result in degradation of image quality as the images will be re-encoded on save. – Ashigore Apr 25 '14 at 10:59
  • Have you tried using `Directory.CreateDirectory(Path.GetDirectoryName(file2))` before the `Copy`? – Damien_The_Unbeliever Apr 25 '14 at 11:00
  • 6
    `\\\ ` isnt that one `\ ` too much? You already have an `@` before the string so you should not need to do additional escaping. (arg, speaking of escaping how do i correctly format my comment to display \ and @ in code tags? :D) – DrCopyPaste Apr 25 '14 at 11:02
  • It is one \ too many but the text wouldnt format properly on the preview so I escaped it for this posting. I will remove it again! – RichardB Apr 25 '14 at 11:11
  • If I do a Directory.CreateDirectory on the destination then DirectoryInfo.Exists returns true. However I still get the exception. Could not find a part of the path '\\node\disk2\dir\file.jpg' – RichardB Apr 25 '14 at 11:27
  • Can you see the new directory on the filesystem after you create it? Also, does the file you are copying to possibly already exist? If so, you need to pass `true` as the third argument (`bool overwrite`) to `File.Copy()`. – shelleybutterfly May 30 '22 at 16:21

1 Answers1

-1

My guess is that the problem is occurring because you are specifying the file name file.jpg in the second parameter. It is considering the entire thing as a directory.

Just try this and check

string file1 = @"\\node\disk1\dir\file.jpg";
string file2 = @"\\node\disk2\dir\"; // Do not specify the file name
File.Copy(file1,file2);
Ajit Vaze
  • 2,686
  • 2
  • 20
  • 24
  • no, what op posted is the correct syntax, for File.Copy you specify the `full path` to both the source and the destination file `The name of the destination file. This cannot be a directory or an existing file. ` from http://msdn.microsoft.com/en-us/library/c6cfw35a%28v=vs.110%29.aspx – DrCopyPaste Apr 25 '14 at 12:23