Open file ReadOnly

前端 未结 4 489
臣服心动
臣服心动 2020-11-27 06:09

Currently, this is how I\'m opening a file to read it:

 using (TextReader reader = new StreamReader(Path.Combine(client._WorkLogFileLoc, \"dump.txt\")))
{
           


        
4条回答
  •  清酒与你
    2020-11-27 06:37

    The typical problem is that the other process has the file open for writing. All of the standard File methods and StreamReader constructors open the file with FileShare.Read. That cannot work, that denies write sharing. You cannot deny writing, the other process was first and got write access. So you'll be denied access instead.

    You have to use FileShare.ReadWrite, like this:

    var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
    using (var sr = new StreamReader(fs))
    {
        // etc...
    }
    

    Beware that you'll still have a tricky problem, you are reading a half-written file. The other process flushes data to the file at random points in time, you may well read only half a line of text. YMMV.

提交回复
热议问题