I have a program, which writes data to a text file in the following format.
test1 - test1 - test1 - test1
After writing the first line, the text fields are cleared to make space for another round of user input. Simply said, this is how it should look:
test1 - test1 - test1 - test1
test2 - test2 - test2 - test2
test3 - test3 - test3 - test3
Here’s my code
If Not File.Exists(path) Then
MessageBox.Show("File doesn't exist in the given path", "No File", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
Else
Dim reader As New StreamReader(path)
reader = File.OpenText(path)
Dim content As String = reader.ReadToEnd
reader.Dispose()
reader.Close()
Dim writer As New StreamWriter(path) 'this is where the exception occurs
writer.Write("Origin : " & Trim(loadOrigin) & vbTab & "-" & vbTab)
writer.Write("Destination : " & Trim(destination) & vbTab & vbCrLf & vbCrLf)
writer.Write(Trim(txtCarrier.Text) & vbTab & "-" & vbTab)
writer.Write(Trim(txtLocation.Text) & vbTab & "-" & vbTab)
writer.Write(Trim(txtDest.Text) & vbTab & "-" & vbTab)
writer.Write(Trim(txtNotes.Text) & vbTab & vbCrLf & vbCrLf)
writer.Close()
MessageBox.Show("Text written to file", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
clearFields()
End If
-
I used
StreamReaderto read the content already inside the text file and reach the end of it to append the new line. However, it shows an IOException error with the message The process cannot access the file ‘D:\test.txt’ because it is being used by another process. It does not help even after I Dispose and/or Close theStreamReader. What am I missing here? -
Would this code fulfill my initial purpose of writing multiple lines to the same text file as I have mentioned above? Do I have to make any changes?
Thank you all very much.
reader.Close()should close the file and release all resources for it. Try closing the file prior to callingDispose(which according to MSDN is not needed because theClosemethod does that for you.Dim writer As New StreamWriter(path, True)will open the file for appending text.Dim writer As New StreamWriter(path)orDim writer As New StreamWriter(path, False)will overwrite the file (if it exists) or create a new file (if it does not exist).If you are still getting the exception, make sure you don’t have the file open elsewhere (like in Notepad).