Accessing a shared file?

守給你的承諾、 提交于 2019-12-11 10:16:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!