In C#, if 2 processes are reading and writing to the same file, what is the best way to avoid process locking exceptions?

前端 未结 8 1971
甜味超标
甜味超标 2020-12-13 04:25

With the following file reading code:

using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
    using (T         


        
8条回答
  •  轮回少年
    2020-12-13 05:28

    Is there any particular reason for opening the file with FileShare.None? That'll prevent the file from being opened by any other process.

    FileShare.Write or FileShare.ReadWrite should allow the other process (subject to permissions) to open and write to the file while you are reading it, however you'll have to watch for the file changing underneath you while you read it - simply buffering the contents upon opening may help here.

    All of these answers, however, are equally valid - the best solution depends on exactly what you're trying to do with the file: if it's important to read it while guaranteeing it doesn't change, then lock it and handle the subsequent exception in your writing code; if it's important to read and write to it at the same time, then change the FileShare constant.

提交回复
热议问题