Read an open File Problem in C# [duplicate]

2019-02-24 09:39发布

问题:

This question already has an answer here:

  • How can I read a file even when getting an “in use by another process” exception? 4 answers

hi I have a program that log some data in text file in specific path.(log.txt) I can open the file (log.txt) with notepad and read what is in it.

now I'm writing a program to read log.txt but I get the exception "The process cannot access the file 'log.txt' because it is being used by another process."

what should I do?

回答1:

Try this:

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

Whether you can open the file depends on the FileShare you've provided when opening the log file. The settings in the example above are quite low and maybe helps opening the file.