user626528
user626528

Reputation: 14399

Accessing a shared file?

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?

Upvotes: 2

Views: 10329

Answers (1)

Svein Fidjest&#248;l
Svein Fidjest&#248;l

Reputation: 3206

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();
    }
}

Upvotes: 7

Related Questions