以只读方式打开文件 [英] Open file ReadOnly

查看:21
本文介绍了以只读方式打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,这是我打开文件以读取它的方式:

Currently, this is how I'm opening a file to read it:

 using (TextReader reader = new StreamReader(Path.Combine(client._WorkLogFileLoc, "dump.txt")))
{
    //do stuff
}

如何以只读模式打开文件,以便在另一个进程同时打开该文件时,我的程序仍然可以读取它.

How can I open the file in ReadOnly mode, so that if another process has the file open at the same time, my program can still read it.

推荐答案

典型的问题是其他进程打开了文件进行写入.所有标准 File 方法和 StreamReader 构造函数都使用 FileShare.Read 打开文件.那行不通,拒绝写共享.您不能拒绝写入,另一个进程首先获得了写入权限.因此,您将被拒绝访问.

The typical problem is that the other process has the file open for writing. All of the standard File methods and StreamReader constructors open the file with FileShare.Read. That cannot work, that denies write sharing. You cannot deny writing, the other process was first and got write access. So you'll be denied access instead.

您必须使用 FileShare.ReadWrite,如下所示:

You have to use FileShare.ReadWrite, like this:

var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
using (var sr = new StreamReader(fs))
{
    // etc...
}

请注意,您仍然会遇到一个棘手的问题,您正在阅读一个写了一半的文件.另一个进程会在随机的时间点将数据刷新到文件中,您可能只会阅读半行文本.天啊.

Beware that you'll still have a tricky problem, you are reading a half-written file. The other process flushes data to the file at random points in time, you may well read only half a line of text. YMMV.

这篇关于以只读方式打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆