Saturday 10 November 2018

command line - 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?



Answer



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()

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...