如何检查文本文件是否打开并关闭文本文件?

时间:2011-07-15 11:24:26

标签: vb.net

我正在尝试将文本文件保存在此路径中:“C:\ Test \ test.txt”,当文件已经打开时,我需要检查文件是否已打开,我需要在写入之前将其关闭到文件。

以下是保存文件的代码:    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

如果我这样做,我可以关闭记事本进程,但我需要关闭特定的打开文本文件:

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 

4 个答案:

答案 0 :(得分:4)

我不相信有一个属性可以让你检查流读取器是否打开。

最佳做法似乎是.close读者完成后。 (全部采用的方法。)

如果你还有一个例外,你可以尝试try block来处理异常。

可以在此处找到其他信息和一些示例代码。祝你好运。

MSDN! StreamReader

编辑:您可以使用此功能进行检查。 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

答案 1 :(得分:2)

怎么样:

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

我的程序附加到电子邮件中的.csv文件出现此问题。我添加了代码以清除MailMessage对象中的Attachments集合,然后在发送邮件后处理MailMessage和Attachment对象。这似乎解决了这个问题。