4

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?

Azhar
  • 20,500
  • 38
  • 146
  • 211

1 Answers1

11

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.

Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
  • 1
    Yup, allowing FileShare.Write is the important one. You can't deny write access, the program already acquired it. – Hans Passant Nov 07 '10 at 12:26
  • I tried this solution but I used only FileShare.Read and it didn't wotk. Now I understand why I should use FileShare.ReadWrite. –  Nov 07 '10 at 12:47