Rajeev Rajeev - 1 year ago 137
C# Question

How to open a file (for reading) which is already opened in another program?

Possible Duplicate:

Open file ReadOnly

In my application I am writing some information to Log.txt using Debug.WriteLine(), and I want to provide a form which will show the contents of Log.txt.

But when I try to open the file Log.txt I am getting an exception:

The process cannot access the file 'F:\Rajeev\10-11-2012\Temp\Temp\bin\Debug\Log.txt' because it is being used by another process.

How do I overcome this problem?

And here another issue is, I am able to open the same file using Notepad. Then why can't I open the same file using my application?

The following is the code I am using for specifying the log file:

TextWriterTraceListener tr = new TextWriterTraceListener(System.IO.File.CreateText("Log.txt"));
Debug.AutoFlush = true;

The following is the code I am using for writing to the log file:

Debug.WriteLine("ERROR: Invalid Username " + s);

The following is the code I am using for opening a log file (which is already opened by "Debug") to show in Log Viewer (a "Form" in my application):

File.Open(LogFilePath, FileMode.Open, FileAccess.Read,FileShare.Read);

Answer Source

This is determined by the permissions the file is opened with. If a program opens the file in any type of exclusive mode, then other programs will have limited or no access.

So you can make sure you don't try to open the file exclusively (you didn't show your code). However, if you don't have the source code for the other program, then you can only hope that that program doesn't open the file exclusively. Otherwise, I don't see what you could do about it except terminate the other program.


The following code:

File.Open(LogFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

Says that other files can also read the file that is open, but I believe they can't write to it. So if the other program was writing to the file, that would not be allowed. You could try FileShare.ReadWrite instead but I'm still not seeing where you've indicated if you have source to the other program. Did I just miss it?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download