我正在使用 Visual Studio 2012 并具有以下代码块。该代码检查特定文件的文件类型(这就是其中返回 True/False 的原因)。如果遇到错误,它也会返回 false。我得到的警告是我在初始化之前使用了 fs/br 变量,这是真的。这就是为什么我有 IsNothing 语句,但我在 IsNothing 语句中收到警告,我不知道如何避免这种情况,因为我不想将fs = New FileStream(fn, FileMode.Open)
andbr = ...
语句放在 Try/Catch 块之外。
代码本身有效,因此警告并不是真正的问题,但拥有它们仍然让我感到困扰。有没有人看到解决方案如何更改此块以在没有警告的情况下提供相同的安全性?
欢迎 VB.NET 或 C# 答案。
Dim fs As FileStream
Dim br As BinaryReader
Try
fs = New FileStream(fn, FileMode.Open) 'Open the file
br = New BinaryReader(fs) 'Initilize the reader
'File reading code omitted here
br.Close() 'Close the reader and underlying stream
Catch
If Not IsNothing(fs) Then fs.Close() 'Warning here
If Not IsNothing(br) Then br.Close() 'and here
Return False
End Try