I am trying to save the text file in this path:"C:Testest.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:Testest.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:Testest.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:Testest.txt"), Diagnostics.Process())
For Each p As Process In Process
p.Kill()
Next
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…