3

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.Listeners.Add(tr);
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);
Community
  • 1
  • 1
Rajeev
  • 843
  • 2
  • 11
  • 22

1 Answers1

3

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.

EDIT

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?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Now i have shown the code in question. Here my question is when Notepad is opening the file, why can't i open the file. – Rajeev Nov 30 '12 at 15:54
  • Here actually i am not creating the Log.txt explicitly, I am just using Debug.Listeners.Add() method and then "Debug" class is creating the file. Now i have shown all the code in my question please see the code. – Rajeev Nov 30 '12 at 16:02
  • I'm having trouble following your logic. Are you responding to the last edit of my answer? That is about an `Open` statement. How is that using `Debug` to create a file? – Jonathan Wood Nov 30 '12 at 16:04
  • Ya now i got your point, and i have changed code to File.Open(LogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); and now its working fine. Thank you – Rajeev Dec 01 '12 at 05:30