D
D
Dmitry Chernyavsky2015-11-06 13:15:44
PowerShell
Dmitry Chernyavsky, 2015-11-06 13:15:44

How to block reading a file while working with it?

Windows, the Powershell script runs every 5 minutes, in the Invoke-WebRequest script it downloads a file from an external server and puts it in a local directory - everything is simple here.
On the same Windows, a certain program regularly reads this file line by line, and if it sees new content in it, it takes it to its database.
The problem is that sometimes the program reads the file at the time of download, as a result, the data appears in the database, but not completely.

How can the script be modified under such conditions so that it blocks the reading of the file by everyone (except itself) during execution? Unfortunately, the program cannot be modified.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
nirvimel, 2015-11-06
@TrK

$file = [System.io.File]::Open('c:\files\somefile.txt', 'Open', 'Write', 'None')

This 'None' in the fourth parameter creates an exclusive lock (like flock in *nix).
If the file is already open for reading by someone, then [System.io.File]::Open will crash with an error.
If the lock is obtained, then calls to open from other programs will fly out with an error.
But it is more reliable to do it through renaming, as already advised here.

V
vaut, 2015-11-06
@vaut

Well, you can definitely download to another place and then replace the file.
There is still flock under linux. Whether there is an analogue for Windows I do not know.

A
alexxandr, 2015-11-06
@alexxandr

using the script, download the file to another location, then copy it to the desired one with the OF_SHARE_EXCLUSIVE flag

M
MrDywar Pichugin, 2015-11-06
@Dywar

The problem is not fully described or what "download" means.
Hundreds of applications can read a file without competing with each other.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question