问题
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?
回答1:
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();
}
}
来源:https://stackoverflow.com/questions/26421683/accessing-a-shared-file