【问题标题】:detecting/preventing error/deadlock when opening/reading text file打开/读取文本文件时检测/防止错误/死锁
【发布时间】:2009-12-21 06:06:52
【问题描述】:

我正在读取带有文本内容的文件。

示例 dictionary.txt 内容:

啊 蕉麻 国外 苹果

片段 A:

Dim path as String = Server.MapPath("dictionary.txt");
Dim dictionary() as String = {}
Try
{
    dictionary = File.ReadAllLines(path)
}
Catch ex as Exception

End Try

片段 B:

Dim path as String = Server.MapPath("dictionary.txt");
Dim dictionary As New List(Of String)
Using  fs As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    Using sr As StreamReader = New StreamReader(fs)
        While Not sr.EndOfStream
            dictionary.Add(sr.ReadLine().Trim())
        End While
    End Using
End Using

在 Snippet A 中,我很少遇到“文件被另一个进程使用”的错误。 在 Snippet B 中,我还没有遇到同样的错误。

基本上,我想确保我可以处理/防止此错误。 Snippet B 是否解决了问题,如果没有,是否有其他方法可以防止此错误。

顺便说一句,这是一个网络应用程序,我期待有多个用户。

【问题讨论】:

    标签: asp.net vb.net deadlock file.readalllines


    【解决方案1】:

    第二个样本对这个问题更稳健,但并不完美。如果文件以独占方式打开,或被外部进程锁定,这仍然会失败。不幸的是,这只是 Windows 系统上的现实。可以通过使用低级api调用来避免这种情况,但是在大多数正常情况下,上述方法通常就足够了。

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2019-09-07
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多