Can I simply 'read' a file that is in use?

后端 未结 2 712
甜味超标
甜味超标 2020-11-29 09:21

I am trying to use a StreamReader to read a file, but it is always in use by another process so I get this error:

The process cannot access the file

2条回答
  •  伪装坚强ぢ
    2020-11-29 09:53

    try the below code.

    FileStream fileStr = File.Open(, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    fileStream = new StreamReader(fileStr);
    

    I have tried it on Windows XP. If the file is already open in write mode by some other process & it has not specified sharing rights, you will still be able to open the file in read mode.

    Disclaimer: It works, but then, I am not sure if you should use it in production code. I am not yet able to find any formal documentation that says it should work.

提交回复
热议问题