Why robocopy still copy an open file, opened by txt editor in windows
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()
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.