D
D
devilya2018-08-09 16:09:57
.NET
devilya, 2018-08-09 16:09:57

How to lock a file for other processes while the program is running?

There is a configuration .json file, and there is an application registered as a windows service that reads and deserializes this file. It is necessary to make this file inaccessible for editing, renaming and deletion by another process for the duration of the service.
Tried opening the file with

var fileStr = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None);

without subsequent closing, but it did not help, the file is still edited and saved. I also tried wrapping the stream in a special class ( https://github.com/colgreen/Redzen/blob/master/Red... ) and this solution was unsuccessful.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
devilya, 2018-08-09
@devilya

The problem was that the file was opened in a class method and assigned to a local variable. It was solved by transferring the variable to the class instance level.

A
Alexander N++, 2018-08-10
@sanchezzzhak

FileStream.Lock()
while the program is running and the file on the lock, only your process can write to the file, anyone can read the locked file.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question