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

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

问题描述

目前,这是如何我打开一个文件来阅读:

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.

推荐答案

典型的问题是,其他的进程打开的书面文件。所有标准文件的方法和构造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天全站免登陆