VB.NET在继续读/写之前检查文件是否打开?
发布时间:2020-12-17 00:13:48 所属栏目:大数据 来源:网络整理
导读:有没有方法来验证文件是否已打开?我唯一能想到的是Try / Catch,看看我是否可以捕获文件打开异常,但我发现如果文件打开,我可以使用一个方法返回true / false. 目前在名为Wallet的类下使用System.IO和以下代码. Private holdPath As String = "defaultLog.txt
有没有方法来验证文件是否已打开?我唯一能想到的是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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |