因为它在被另一个进程使用流阅读器进程无法访问文件 [英] Stream Reader process cannot access file because its in use by another process

查看:155
本文介绍了因为它在被另一个进程使用流阅读器进程无法访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序解析日志文件,但试图解析当前日期的文件时,我得到一个错误,指出该文件正被另一个进程。该日志文件当前正在写入,并且可以通过记事本,但不能被访问,通过我的申请。

My application parses log files but when trying to parse the current day's file I get an error stating that the file is being used by another process. This log file is currently being written to and can be accessed through notepad but not through my application.

目前的code:

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

也试过,但没有运气:

Also tried this but had no luck:

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

什么样的​​变化需要是我的code,以读取正在由另一个进程使用的文件。复制日志文件不是一个解决方案,由于日志我的应用程序的大小和性能

What changes need to be to my code in order to READ a file that is being used by another process. Copying the log file is not a solution due to the size of the log and performance of my application

推荐答案

我们可以使用的不同的签名与读/写访问到其他进程打开文件流:

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);

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.

您最初的code座将默认为 FileShare.None

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".

这篇关于因为它在被另一个进程使用流阅读器进程无法访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆