2

I'm trying to allow just one process be able to write to a file and other processes could only read it , so I tried to open the file by:

sw = new StreamWriter(File.Open(filepath, FileMode.Create, FileAccess.Write, FileShare.Read));

and then there is a write loop:

while(true)
{   
//some code
    sw.Write(message);
}

sw.close();

while this process writes to the file, I tried to open it manually I recive a message to open the file in readonly mode , when I press "readonly" button the writer process throws exception "System.IO.IOException: The process cannot access the file because another process has locked a portion of the file."

how I could fix it ?

MajdwWTD
  • 21
  • 1
  • I don't believe you can make this work, and will need to consider different approaches, see e.g. https://stackoverflow.com/questions/3507770/write-to-a-file-from-multiple-threads-asynchronously-c-sharp – doctorlove Jun 12 '19 at 15:44
  • follow up with previous comment check this article too [multiple process write file](https://stackoverflow.com/questions/18690537/multi-processes-readwrite-one-file) – Power Mouse Jun 12 '19 at 15:46
  • I have tried your code and don't see any issues if you are just wanting to monitor the file try opening it with baretail https://www.baremetalsoft.com/baretail/ – Jake Steffen Jun 12 '19 at 15:47
  • 1
    Could you explain what you mean by "open it manually"? – Jim Rhodes Jun 12 '19 at 15:49
  • I tried to open it by myself, not by another code , the OS release the lock for specific time and then the writer process acquire it again and continue to work normaly – MajdwWTD Jun 12 '19 at 15:58
  • So, if the lock is temporary, catch the exception and perform some number of retries perhaps with a delay between each retry. – Jim Rhodes Jun 12 '19 at 16:18

0 Answers0