File.ReadLines 没有锁定吗?
情况下打开文件流
new FileStream(logfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
我可以在不锁定文件的
。我可以用 File.ReadLines(string path) 做同样的事情吗?
I can open a FileStream with
new FileStream(logfileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Without locking the file.
I can do the same with File.ReadLines(string path)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不...如果您使用 Reflector 查看,您会发现最终
File.ReadLines
打开一个FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, FileOptions.SequentialScan);
所以只读共享。
(从技术上讲,它使用
FileStream
打开一个StreamReader
,如上所述)我要补充的是,创建一个静态方法来执行此操作似乎是小菜一碟:
这会返回一个
IEnumerable
(如果文件有数千行并且您一次只需要解析它们,那就更好了)。如果您需要数组,请使用 LINQ 将其调用为ReadLines("myfile").ToArray()
。请注意,从逻辑上讲,如果文件“在(方法的)背后”发生更改,那么一切将如何工作是相当未定义的(它可能是技术上定义的,但定义可能相当长且复杂)
No... If you look with Reflector you'll see that in the end
File.ReadLines
opens aFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, FileOptions.SequentialScan);
So Read-only share.
(it technically opens a
StreamReader
with theFileStream
as described above)I'll add that it seems to be child's play to make a static method to do it:
This returns an
IEnumerable<string>
(something better if the file has many thousand of lines and you only need to parse them one at a time). If you need an array, call it asReadLines("myfile").ToArray()
using LINQ.Please be aware that, logically, if the file changes "behind its back (of the method)", how will everything work is quite undefined (it IS probably technically defined, but the definition is probably quite long and complex)
File.ReadLines()
将锁定文件直到完成。File.ReadLines()
will lock the file until it finishes.