0
file.CopyTo(destinationFullName , true);

if (destinationFullName == file.FullName) {
      logTrace(TraceEventType.Information, "Overwritten file " + file.FullName + " with " + destinationFullName);
 }

Is there a good way to detect if a file is being overwritten instead of manually comparing file name of source and destination. I was like to log a message if CopyTo overwrites a file.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Lightsout
  • 3,454
  • 2
  • 36
  • 65
  • 3
    **Hint:** [FileInfo.Exists](https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo.exists?view=net-5.0). Before `.CopyTo`. – dr.null Aug 06 '21 at 22:58
  • But realize that there's a race condition lurking in there (pretty much an unavoidable race condition). – Flydog57 Aug 06 '21 at 23:22
  • No, FileInfo.Exists is not good enough. – Joel Coehoorn Aug 07 '21 at 01:00
  • If you don't want to use FileExists before copy, there is no WinAPI (in the case of Windows) to copy a file and get a value indicating whether the file was created new or was overwritten, as I know. Therefore, you need to create your own method using for example a stream, perhaps, which will be like: `FileCopyResult CopyFile(string source, string target, bool overwrite);` where `FileCopyResult` can be `{Created, Overwritted}` and you will raise any standard exceptions. [Sample 1](https://stackoverflow.com/questions/6044629/) • [Sample 2](https://stackoverflow.com/questions/16982277/) –  Aug 07 '21 at 03:16

1 Answers1

2

If you don't want to check if the file exists before you try to copy, you could use the File.Copy() method where it says right in the documentation that overwriting a file is not allowed:

Copies an existing file to a new file. Overwriting a file of the same name is not allowed.

...

IOException
destFileName exists.

So you could put the Copy in a try, and then catch an IOException that would indicate that the file already exists. See the link I pasted for more information.

I am sure you have a good reason for not wanting to check for the existence of the file in advance. I don't normally recommend using a try catch block like this though.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
David.Warwick
  • 620
  • 1
  • 9
  • 28
  • fwiw, `File.Exists()` is [kind of bad](https://stackoverflow.com/a/265958/3043), and this is the correct way to do it :) – Joel Coehoorn Aug 07 '21 at 01:11
  • I see your point. The file system can be tricky and unpredictable, especially on a network with multiple users. – David.Warwick Aug 07 '21 at 01:14
  • I do want to overwrite the file though I just want to make a note if that happens. So are you saying to copy again if exception triggers? – Lightsout Aug 07 '21 at 01:29
  • 1
    You could do that from the catch block. If your code goes into the catch block with a destFileName exists exception, you could then log it and then overwrite the file. – David.Warwick Aug 07 '21 at 01:34