有没有方法来验证文件是否已打开?我唯一能想到的是Try / Catch,看看我是否可以捕获文件打开异常,但我发现如果文件打开,我可以使用一个方法返回true / false.
目前在名为Wallet的类下使用System.IO和以下代码.
Private holdPath As String = "defaultLog.txt" Private _file As New FileStream(holdPath,FileMode.OpenOrCreate,FileAccess.ReadWrite) Private file As New StreamWriter(_file) Public Function Check(ByVal CheckNumber As Integer,ByVal CheckAmount As Decimal) As Decimal Try file.WriteLine("testing") file.Close() Catch e As IOException 'Note sure if this is the proper way. End Try Return 0D End Function
任何指针将不胜感激!谢谢!!
Private Sub IsFileOpen(ByVal file As FileInfo) Dim stream As FileStream = Nothing Try stream = file.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.None) stream.Close() Catch ex As Exception If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then ' do something here,either close the file if you have a handle,show a msgBox,retry or as a last resort terminate the process - which could cause corruption and lose data End If End Try End Sub Private Shared Function IsFileLocked(exception As Exception) As Boolean Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1) Return errorCode = 32 OrElse errorCode = 33 End Function