Below is the code ,where i am checking a specified file is opened or not and if opened i am closing or else deleting.
There is no built in functionality in .Net to check ISFILEOPEN.
So we are forcebily trying to read the ,so if its not opened it will through a exception & there we can write the code for if file is not opened.
Using f As New IO.FileStream("C:\1.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.None)
If the file is in shared mode we have to check as below
Using f As New IO.FileStream("C:\1.xlsx", FileMode.Truncate, FileAccess.ReadWrite, FileShare.None)
Filemode.truncate will check it in shared mode.
Dim thisFileInUse As Boolean = False
If System.IO.File.Exists("C:\1.xlsx") Then
Try
Using f As New IO.FileStream("C:\1.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.None)
' thisFileInUse = False
End Using
IO.File.Delete("C:\1.xlsx")
Catch
thisFileInUse = True
nFiles = excel.Workbooks.Count
For iVar = 1 To nFiles
If UCase(excel.Workbooks(iVar).Path & "\" & excel.Workbooks(iVar).Name) = UCase("C:\1.xlsx") Then
excel.Workbooks(iVar).Close()
End If
Next
End Try
End If
There is no built in functionality in .Net to check ISFILEOPEN.
So we are forcebily trying to read the ,so if its not opened it will through a exception & there we can write the code for if file is not opened.
Using f As New IO.FileStream("C:\1.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.None)
If the file is in shared mode we have to check as below
Using f As New IO.FileStream("C:\1.xlsx", FileMode.Truncate, FileAccess.ReadWrite, FileShare.None)
Filemode.truncate will check it in shared mode.
Dim thisFileInUse As Boolean = False
If System.IO.File.Exists("C:\1.xlsx") Then
Try
Using f As New IO.FileStream("C:\1.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.None)
' thisFileInUse = False
End Using
IO.File.Delete("C:\1.xlsx")
Catch
thisFileInUse = True
nFiles = excel.Workbooks.Count
For iVar = 1 To nFiles
If UCase(excel.Workbooks(iVar).Path & "\" & excel.Workbooks(iVar).Name) = UCase("C:\1.xlsx") Then
excel.Workbooks(iVar).Close()
End If
Next
End Try
End If