Nishant
Nishant

Reputation: 905

FileInfo CopyTo method throwing an IOException (.net)

The CopyTo method of FileInfo class throws an IOException

The process cannot access the file 'C:\Data\Test.XML' because it is being used by another process.

Any ideas on why this should happen? I understand that copying a file just requires read access. So ideally even if the file is write protected or is opened by some other program the CopyTo should have no problem executing.

FileInfo copyFile = null;

//currentFile.FileInformation is of type FileInfo which is referring to the file for which a copy is being created. In this case it is C:\Data\Test.XML
System.IO.FileInfo file = new FileInfo(currentFile.FileInformation.FullName);

// Constructing name for the temporary copy of Test.XML
string newName = "Temp Copy of " + currentFile.FileInformation.Name;

//This is where I get the exception. The CopyTo fails...
copyFile = file.CopyTo(System.IO.Path.Combine(currentFile.FileInformation.DirectoryName, newName), true);

fs = System.IO.File.Open(copyFile.FullName, FileMode.Open);

Also some important points to note :

Please let me know if I can provide you with any more details

Thanks in advance

Upvotes: 0

Views: 3600

Answers (3)

Aliostad
Aliostad

Reputation: 81680

  • Download sysinternal's process explorer
  • put a breakpoint on File.CopyTo
  • in process explorer, search for the file name, it will tell you which process got it open

Upvotes: 2

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263077

Another process might have specified the FILE_SHARE_READ mode when it opened the file, which would prevent you from even reading it.

You can use Process Explorer to find that process.

Upvotes: 0

Bernard
Bernard

Reputation: 7961

If you're using Windows, try using Process Explorer to determine what process is using the files you are trying to copy.

Upvotes: 0

Related Questions