访问共享文件?

时间:2014-10-17 09:11:48

标签: c# .net shared-directory windows-share

我试图通过它的UNC路径从Windows共享文件夹中读取文件正文,并获得此异常:The process cannot access the file '\\<someIP>\logs\LogFiles\W3SVC1\u_ex141017.log' because it is being used by another process.
但是,此文件并未被任何进程锁定。我可以使用文本编辑器等从我的电脑上查看它。

我使用此代码读取文件:

var logFile = File.ReadAllText(logPath);

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

(都失败)

当文件未被任何进程真正锁定时,为什么会出现此异常的任何想法?

1 个答案:

答案 0 :(得分:4)

尝试将FileShare.Delete更改为FileShare.ReadWrite。这将允许文件同时由其他应用程序读取和写入。换句话说

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