On the ball is a file with DateTime .

On different servers, spinning 2 (or more) instances of the same application that access the file on the ball, take time from it and record the new time.

I use

 using (var fs = new FileStream(dateFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) 

And then I read the time and try to overwrite the new time with

 using (var sw = new StreamWriter(fs)) 

But such use leads to writing , rather than overwriting the file.

  1. How to organize exclusive access to a file so that no one else can read information from it (and even more so)?

  2. How to overwrite a file? (Here you probably need to use fs.Seek(0, SeekOrigin.Begin) and without using the StreamWriter class)

    1 answer 1

    Try this:

     using (var fs = new FileStream(dateFile, FileMode.Truncate, FileAccess.Write, FileShare.None) 

    I read your question incorrectly, you read the time, then you need to:

     using (var fs = new FileStream(dateFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None) 

    This code should set the write position to the beginning of the file, and there should be no problem with overwriting the value. But what is likely, if you first read and then write, then the position of the stream will be shifted, so after reading the old value set the position to the beginning: fs.Seek(0, SeekOrigin.Begin) and after that create a stream on Record ( StreamWriter ).

    • Yeah, FileShare.ReadWrite means reading or writing - VladD
    • And in this case, I will not be able to read the value before changing it due to FileMode.Truncate . Or I did not understand this mod? - Vladislav Vitalyev
    • @VladislavVitalyev, updated the answer - ixSci
    • @ixSci, thanks for the detailed answer. As I understand it, in this case, the second instance will receive an IOException, which I can easily treat as a Thread.Sleep(5000) and retry accessing the file. - Vladislav Vitalyev February
    • one
      @VladislavVitalyev, yes, that's it. But I would not wait so long. You have quite a fast operation, you can try not to wait at all, but try again right away. - ixSci