VB.NET Checking file open before continuing to read / write?

Is there a way to verify that the file is open? The only thing I can think of is Try/Catch to see if I can catch an exception with an open file, but I decided that the method would be available to return true / false if the file was open.

Currently, System.IO used and the following code is under a class called Wallet .

  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 

Any pointers would be appreciated! Thanks!

+7
source share
3 answers
 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 
+14
source

In fact, it makes no sense to use the "use file for verification" function, since you still need to try to catch in order to handle the case when the file does not open. Opening a file may fail for many reasons, not just opening.

Also, using the function for verification is not a guarantee of success. A β€œfile usage check” can return false only so that the file is opened with an error with a file error already opened, because the time between the check and the attempt to open the file was opened by someone else.

+5
source

It looks like the two sentences from this MSDN forum post include trying to open the file.

The first is similar to what you are doing now, and the second includes using the Windows API (CreateFile) function and checking for an invalid handle meaning the file is in use. In both cases, they rely on the error condition to determine if the file is open or not. In short, in my opinion, the method you use is correct, since the property does not have the System.IO.File.IsOpen property.

+1
source

All Articles