Hi,
I am having trouble removing a line from a text file. When I click on the button in order to remove the line it gives me an error that access to the file is not possible. Now I assume that the file is in use during me wanting to change it and therefore cant save it while it is loaded in ht application. I have tried a few things but cant seem to get it to work.
Essentially what it does is that I have another dialog that a used can add data, the data is then written to the file FilingLocations.txt and then it saves it and loads it again. But once the line is no longer needed I would like to have the option to remove the line again. Any advise.
Here is the code:
Private Sub cmdRemoveLocation_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRemoveLocation.Click
Dim txtFilingFile As String
Dim objStreamWriter As StreamWriter
Dim WriteToFileSave As StreamWriter
Dim TheFileLines As New List(Of String)
Dim TheFileLineTransfer As New List(Of String)
Dim txtFilinglocations As String = My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData.ToString()
Dim LineNumberLocator As Integer
Try
If Not (txtFilinglocations.EndsWith("\")) Then
txtFilingFile = txtFilinglocations & "\" & "FilingLocations.txt"
Else
txtFilingFile = txtFilinglocations & "FilingLocations.txt"
End If
If tbLineNo.Text = "" Then
MsgBox("Please select a line to delete", CType(vbOKOnly, MsgBoxStyle), "Error Deleteing Line")
ElseIf tbLineNo.Text <> "" Then
LineNumberLocator = CInt(tbLineNo.Text.ToString)
If Not (File.Exists(txtFilingFile)) Then
objStreamWriter = New StreamWriter(txtFilingFile)
MsgBox("File does not exist, file has now been created", vbOKOnly, "File Created")
'Exit Sub
ElseIf File.Exists(txtFilingFile) Then
Using sr As New StreamReader(txtFilingFile)
TheFileLines.AddRange(System.IO.File.ReadAllLines(txtFilingFile.ToString))
TheFileLineTransfer = TheFileLines
sr.Dispose()
sr.Close()
End Using
If CDbl(LineNumberLocator) >= TheFileLines.Count Then Exit Sub
TheFileLineTransfer.RemoveAt(CInt(LineNumberLocator))
WriteToFileSave = New StreamWriter(txtFilingFile, True)
WriteToFileSave.Write(TheFileLineTransfer.ToArray)
WriteToFileSave.WriteLine()
WriteToFileSave.Close()
Else
MsgBox("Text file not found in " & My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData.ToString())
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub