sharptooth
sharptooth

Reputation: 170549

Can't read the file but can copy it in C#

There's a log file that is used by some system service. I want my program to read that file.

If I use System.IO.File.ReadAllText() I get System.IO.IOException with The process cannot access the file 'X' because it is being used by another process. message. Yet if I call System.IO.File.Copy() I can copy that file into a temporary file and read the temporary file.

This is somehow weird. If I can copy the file why can't I just open it for reading?

Is it possible to just read that file in place without copying it first?

Upvotes: 1

Views: 231

Answers (2)

Oscar
Oscar

Reputation: 13990

It depends how the log file was created, specially the FileShare parameter. You can set it to allow read, write or none.

FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read); 

http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

Upvotes: 2

mbarthelemy
mbarthelemy

Reputation: 12913

The message you got means that this log file was created/opened without the 'share read' flag. Indeed, opening a file that is already opened is only allowed if the creator or first 'opener' of this file explicitely allowed it.

To read it, you can copy it, as you already did, or create a VSS snapshot of your drive.

Upvotes: 0

Related Questions