在C#中读取一个打开的文件问题

嗨,我有一个程序,在特定路径的文本文件中记录一些数据。(log.txt)我可以用记事本打开文件(log.txt)并读取其中的内容。

现在我正在编写一个程序来读取log.txt,但我得到了exception“进程无法访问文件’log.txt’,因为它正被另一个进程使用。”

我该怎么办?

试试这个:

using (var stream = File.Open("log.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var reader = new StreamReader(stream)) { // Actions you perform on the reader. } 

是否可以打开文件取决于打开日志文件时提供的FileShare 。 上面示例中的设置非常低,可能有助于打开文件。