0

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

Further to above question, how could it be the simplest way to keep an file opened in a bare windows env like server 2016 environment to show the robocopy properties that it will avoid copying opened file or even show error in log for testing purpose?

either by batch or other existing function in windows server could be acceptable

VBS sth like this does not work

Set MyFile = fso.OpenTextFile(FileName, ForWriting, True)

Do MyFile.WriteLine "Hello world!" Loop

0

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

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. Some scripting interpreters will always use "share all".

However, you can use any .NET-runtime language and the 4-parameter System.IO.File.Open() function. Chances are that your Windows system has a C# compiler (csc.exe) hidden somewhere, but nowadays it's easier to do the same in PowerShell:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.