1

I am trying to save the text file in this path:"C:\Test\test.txt" and when the file is already opened I need to check whether the file is opened and I need to close it before writing it to the file.

Here is the code for saving the file: Dim myfile As String = "C:\Test\test.txt"

    'Check if file exists
    If System.IO.File.Exists(myfile) = True Then
        'Delete it!

        Dim fi As New FileInfo(myfile)
        fi.Delete()
    End If



    Using sfdlg As New Windows.Forms.SaveFileDialog
        sfdlg.DefaultExt = "amk"
        sfdlg.Filter = "AquaMark Project|*.amk"
        If sfdlg.ShowDialog = Windows.Forms.DialogResult.OK Then


            Dim SaveData As New gCanvasData


            IO.Directory.CreateDirectory("C:\Test")
            Dim w As New IO.StreamWriter("C:\Test\test.txt")
            Dim i As Integer


            For i = 0 To CheckedListBox1.Items.Count - 1
                w.WriteLine(CheckedListBox1.Items.Item(i))
            Next
            w.Close()
            With SaveData
                frmDisplay.GCanvas1.UnselectCurrentAnotate()
                .gAnnotates = frmDisplay.GCanvas1.gAnnotates
                .Image = frmDisplay.GCanvas1.Image
            End With

            Using objStreamWriter As New StreamWriter(sfdlg.FileName)
                Dim x As New XmlSerializer(GetType(gCanvasData))
                x.Serialize(objStreamWriter, SaveData)
                objStreamWriter.Close()
            End Using
        End If
    End Using

If I am doing this way I am able to close the notepad process but I need to close the specific opened text file:

Dim Process() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")
Process() = CType(Interaction.GetObject("C:\Test\test.txt"), Diagnostics.Process())
For Each p As Process In Process
    p.Kill()
Next 
dustinrwh
  • 888
  • 1
  • 14
  • 16

5 Answers5

4

I do not believe there is a property that will allow for you to check if the streamreader is open or not.

Best practice seems to be to .close the reader when done with it. (All in the method that it was used in.)

You could try a try block to handle the exception if you are still getting one.

May be able to find additional info and some sample code here. Good Luck.

MSDN! StreamReader

EDIT: You may be able to check using this. IO.File

Private Function CheckFile(ByVal filename As String) As Boolean

    Try
        System.IO.File.Open(filename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
        FileClose(1)
        Return False
    Catch ex As Exception
        Return True
    End Try

End Function
dustinrwh
  • 888
  • 1
  • 14
  • 16
sealz
  • 5,348
  • 5
  • 40
  • 70
2

What about :

If File.Exists("File1.txt") = False Then
            File.CreateText("File1.txt").Close()
        Else
            Exit Sub
        End If

        If File.Exists("File2.txt") = False Then
            File.CreateText("File2.txt").Close()
        Else
            Exit Sub
        End If
End If
dustinrwh
  • 888
  • 1
  • 14
  • 16
2
Private Sub IsFileOpen(ByVal file As FileInfo)
    Dim stream As FileStream = Nothing
    Try
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
    Catch ex As IOException 

        If IsFileLocked(ex) Then
          'do something here, either wait a few seconds, close the file if you have  
          'a handle, make a copy of it, read it as shared (FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.ReadWrite). 
          'I dont recommend terminating the process - which could cause corruption and lose data
        End If
    Catch ex As Exception

    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
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • use `catch ex as IOException` before `ex as Exception` to catch the exception type. – fcm Nov 01 '16 at 15:23
1

The following function can be used to determine is a file is already open (True) or not (False). Action can then be based on the Function result.

Public Function IsFileOpen(ByVal xFileName As String, ByVal xFileChannel As Integer) As Boolean
    ' ************************************************************
    ' * Function: IsFileOpen
    ' * Purpose:  To determine if a file is already open.
    ' *           Can be used to determine if a file should be closed.
    ' * Syntax:
    ' *     Dim bResult as Boolean
    ' * 
    ' *     bResult = IsFileOpen("C:\Test.txt", 1) 
    ' * 
    ' *     OR
    ' * 
    ' *     If IsFileOpen("C:\Test.txt", 1) = True Then
    ' *         Microsoft.VisualBasic.FileClose(1)
    ' *     End If
    ' * 
    ' ************************************************************
    Try
        Microsoft.VisualBasic.FileOpen(xFileChannel, xFileName, OpenMode.Input, OpenAccess.Read, OpenShare.Default)
    Catch
        ' File Already Open Error Number = 55
        If Trim(Err.Number.ToString) = "55" Then
            Return True
        Else
            Return False
        End If
    End Try
End Function
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Dan
  • 11
  • 1
0

I was having this problem with a .csv file my program attaches to an email. I added code to clear the Attachments collection in the MailMessage object then disposing the MailMessage and Attachment objects after the mail is sent. That appears to have fixed the problem.

Jon Boy
  • 11
  • 1