Stream Reader process cannot access file because its in use by another process [duplicate]

馋奶兔 提交于 2019-12-01 09:36:23

We can use a different signature for opening the filestream with read/write access to other processes:

Stream stream = new FileStream(fileToRead, FileMode.Open, FileAccess.Read,
                        FileShare.ReadWrite);

or

Stream stream = File.Open(fileToRead, FileMode.Open, FileAccess.Read,
                        FileShare.ReadWrite);

The FileShare option determines how other processes can access the same file when this process opens the same file.

Your first code block will default to FileShare.None:

Stream stream = new FileStream(fileToRead, FileMode.Open, FileAccess.Read);

This would fail whilst the file is open as it's trying to obtain exclusive access to the file.

However, you would need this to occur in the log writer to allow your log reader to have read access.

Lastly, try running your log reader as an administrator, as there may be operating system permissions at play that are not obvious when you "open with notepad".

Here is a code snippet

The problem is when another application opens it first and the file sharing is Read only (FileShare.Read) certainly you can't write onto the file but you can read, Or file sharing is Write only (FileShare.Write) you can't Read onto the file but still you can be write onto it.

 using (FileStream file = new FileStream("You File Name here", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            using (StreamReader sr = new (StreamReader (file))
            {
        //Do your codes here     
            }
        }

I had a similar problem that was resolved by setting the file attributes.

File.SetAttributes(outputDirectory + fileName + ".txt", FileAttributes.Normal);

This was done after the file was created, though. The problem has to do with how the OS manages files that are being accessed by multiple processes. In my case, I deleted the file (you aren't always allowed to do this because you'll get the error you're seeing). The only real way to solve this is to track down the processes that are accessing the file and stop them. The easiest way I fix this is restarting my PC, but if you are working on a server, that isn't feasible to do.

I haven't done an extensive amount of testing, but if you wanted to get this to be used by multiple processes, maybe it might be a good idea to give the file read properties and/or attributes:

File.SetAttributes(outputDirectory + fileName + ".txt", FileAttributes.ReadOnly);

Good luck - hope this helps someone else out there (since this is already a year old!).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!