Why robocopy still copy an open file, opened by txt editor in windows

From wikipedia, it is told that robocopy will skip copying files in open status.

However, when it is under test for robocopy behaviour, the robocopy still copy the opened file by the most simple text editor in windows. Why?


Solution 1:

First, as @fejyesynb correctly noted, Notepad doesn't keep an active file handle – it opens the file, quickly reads (or writes) the data, and closes the file again. The data is on screen, but the file is actually closed the whole time.

Second, Windows has inherited from MS-DOS the concept of "share modes" as a simple form of file locking. When opening a file you can choose whether to share it for read/write, for only reading, or not at all.

For example, if your program (robocopy) wants to open the file for reading (FileAccess.Read), it will only succeed if all existing file handles allow the 'read' share mode (or if there aren't any open file handles at all). But if the file was opened with "share none", then you'll get "File in use" if you try to open it for any purpose.

You can perform this in PowerShell, by calling the low-level .NET System.IO.File.Open() function:

$fh = [System.IO.File]::Open($path,
                             [System.IO.FileMode]::Open,
                             [System.IO.FileAccess]::Read,
                             [System.IO.FileShare]::None)

The 4th parameter can be any System.IO.FileShare enum value, for example:

  • [System.IO.FileShare]::None – share nothing
  • [System.IO.FileShare]::Read – share read (block write/delete)
  • [System.IO.FileShare]::ReadWrite – share read/write (block delete)

When you're done:

$fh.Close()

Solution 2:

Because you are thinking of a different meaning of "open".

Notepad (and all other text editors I know) opens a file for reading, then you see it on your screen. Then it closes the file while you can still see the contents (now in RAM).

If, for example, you have fd = open("file.txt", FLAGS); and it isn't (yet) closed by close(fd), then it wouldn't be copied with robocopy.

Solution 3:

Depends on how the file is opened!

Many applications load the whole file to memory and close it, thus in fact the file is not in used. This of course can't be used with huge files, therefore editors for large text files have various techniques to work efficiently, like loading a part of the file to memory at once

Many others do keep the file handle opened, but they don't lock the file

Notepad OTOH maps the file to memory, resulting in a file that doesn't look like being opened. That means what fejyesynb said is not correct, because it doesn't load the file to RAM

For more information you can read

  • Why is Windows not warning about file in use for certain programs?
  • Notepad beats them all?
  • Powershell: Get-Content without locking file