问题描述
我试图将文本文件保存在此路径中:C:\Test\test.txt",当文件已经打开时,我需要检查文件是否已打开,在写入之前需要关闭它到文件.
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.
这是保存文件的代码:Dim myfile As String = "C:\Test\test.txt"
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
推荐答案
我不相信有一种属性可以让您检查流阅读器是否打开.
I do not believe there is a property that will allow for you to check if the streamreader is open or not.
最佳实践似乎是在阅读器完成后.close
.(都在使用它的方法中.)
Best practice seems to be to .close
the reader when done with it. (All in the method that it was used in.)
如果您仍然遇到异常,您可以尝试使用 try 块
来处理异常.
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.
您可以使用它进行检查.IO.File
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
这篇关于如何检查文本文件是否打开并关闭文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!