File.ReadAllLines()紧随其后的是File.WriteAllLines(),由于锁定导致异常

编程入门 行业动态 更新时间:2024-10-09 00:47:19
本文介绍了File.ReadAllLines()紧随其后的是File.WriteAllLines(),由于锁定导致异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的程序中,我有一大堆可以做到的代码

In my program I have a chunk of code that does

var lines = File.ReadAllLines(myFileName); if (lines[0] != null) { //does a few things File.WriteAllLines(myFileName, lines); }

虽然起初工作得很好,但是最近它给了我一个例外,因为该文件大约90%的时间被另一个进程使用.这对我来说已经毫无意义,因为 File.ReadAllLines()应该在读取后关闭文件.我在 File.WriteAllLines()之前添加了 System.Threading.Thread.Sleep(3000),这使我的成功率提高到了50%.睡线并交叉手指真的是我唯一的选择吗?我找不到任何人对 File.ReadAllLines()有类似问题的消息来源.

While this worked fine at first, recently it has given me an exception due to the file being used by another process ~90% of the time. This already made no sense to me since File.ReadAllLines() is supposed to close the file after reading. I added System.Threading.Thread.Sleep(3000) right before the File.WriteAllLines(), which increased my success rate to ~50%. Is sleeping the thread and crossing my fingers really my only option? I can not find any sources where people have had similar issues with File.ReadAllLines().

任何建议,解释或实际修复都将有所帮助.我忍不住想要失去一些东西.

Any suggestions, explanation, or practical fixes would help. I can't help but feel like I'm missing something.

以实际代码编辑了我的if语句

edited my if statement with the actual code, incase it matters

我正在将文件读写到网络共享中,而不是本地计算机中.

I am reading and writing the file to a network share, not my local machine.

这似乎不是我的应用程序在文件上的任何挂起版本,通过使用这个问题,是我的应用程序对该文件进行了锁定.

It does not appear to be any kind of hung version of my app holding on to the file, and from what I can tell by using the FileUtil class in this question, it is my app that has a lock on the file.

推荐答案

我已经弄清楚了问题所在.在达到此代码之前,有一些较旧的旧版"代码由于过时的原因而快速读取文件.我们使用的许多旧版代码对流的使用都很草率,最近我一直在回溯并清理它,并在不使用任何地方的地方实施正确的 using()语法.显然我错过了一个地方,并且有一个旧的 StreamReader 从未被丢弃过.感谢大家的评论,在此过程中学到了一些东西.

I have figured out what the issue was. Prior to this code ever being reached, there was some older "legacy" code that quickly read the file for what is now an outdated reason. A lot of the legacy code we have has very sloppy use of streams, and I have recently been going back and cleaning it up and implementing proper using() syntax wherever it wasnt being used. Apparently I missed a spot, and had an old StreamReader that was never being disposed of. Thanks to everyone for the comments, learned some things in the process.

更多推荐

File.ReadAllLines()紧随其后的是File.WriteAllLines(),由于锁定导致异常

本文发布于:2023-11-03 23:56:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556423.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:的是   异常   File   ReadAllLines   WriteAllLines

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!