Reputation: 7278
I have looked at many posts with the similar title and their suggested answers. But they haven't solved my problem. Examples are this, this and this.
I have a text file that is always locked by a Windows Service (it's a logger basically). What I want to do is to read from this file in my program and also be able to empty its contents.
Do we have a working solution that does not include copying the file?
This is my code for reading the file so far and it of course is not currently working.
serviceLogs = new List<string>();
try
{
//Lock Exclusively the file
using (FileStream fileStream = new FileStream(Globals.serviceLogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fileStream))
{
String line;
while ((line = sr.ReadLine()) != null)
serviceLogs.Add(line);
}
}
Upvotes: 0
Views: 141
Reputation: 8551
If you can change the service, I recommend adding some form of inter-process communication whereby the client program can request a copy of the data and, either in the same request or another, ask the server to clear the file. I've never used WCF, but from what little I know it sounds like it was designed for this type of thing. If you want a third-party solution for IPC, I recommend Ice from ZeroC.
Upvotes: 1
Reputation: 108880
A few different approaches:
Don't share a plain file between the service and the program.
Perhaps a pipe or socket is better for your application.
Reduce the time the service keeps the file open. For example by using File.AppendAllLines
or File.AppendAllText
.
This can still lead to lock conflicts, but you should be able to handle them by retrying.
Don't clear the file from the program. Have it send a message to the service which then clears the file.
Taking this approach one step further, you wouldn't even read the file from the program, but query the service.
Change both the service and the program so they open the file with permissive sharing flags.
Both service and program should use FileShare.ReadWrite
. This has the risk of conflicting operations corrupting the data.
Upvotes: 1