2

I'm trying to read a file body from a Windows shared folder by it's UNC path, and getting this exception: The process cannot access the file '\\<someIP>\logs\LogFiles\W3SVC1\u_ex141017.log' because it is being used by another process.
However, this file isn't really locked by any process. I can view it from my PC using a text editor, etc.

I'm using this code to read the file:

var logFile = File.ReadAllText(logPath);

and

var logFile = (string)null;
using (var fileStream = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.Delete))
{
    using (var reader = new StreamReader(fileStream))
    {
        logFile = reader.ReadToEnd();
    }
}

(both fail)

Any ideas why this exception might happen, when the file isn't really locked by any process?

user626528
  • 13,999
  • 30
  • 78
  • 146

1 Answers1

7

Try changing FileShare.Delete to FileShare.ReadWrite. This will allow the file to be read and written by other applications simultaneously. In other words

var logFile = (string)null;
using (var fileStream = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (var reader = new StreamReader(fileStream))
    {
        logFile = reader.ReadToEnd();
    }
}
Svein Fidjestøl
  • 3,106
  • 2
  • 24
  • 40
  • I thought this can't work, as FileShare.ReadWrite is more access restrictive than FileShare.Delete. But it does. Why? – user626528 Oct 17 '14 at 09:39
  • 1
    Delete and ReadWrite in fact mean two quite different things. From MSDN: http://msdn.microsoft.com/en-us/library/system.io.fileshare(v=vs.110).aspx **Delete:** Allows subsequent deleting of a file. **ReadWrite:** Allows subsequent opening of the file for reading or writing. – Svein Fidjestøl Oct 17 '14 at 09:40
  • Unfortunately, it doesn't work. I am still facing with the problem. I am using .net core 3.1 on Mac with the same code "FileShare.ReadWrite", and same error System.IO.IOException: The process cannot access the file '../log_1.txt' because it is being used ber process. I can open the file with vs code – HalfLegend Jun 03 '20 at 07:32