I have an application that creates a text file if the file doesn't already exist and then writes something to it. It works great the first time through, when I am creating and immediately writing to the file. My problem is that the next time this code executes and the file is already created, it throws an exception when I am trying to write to the file. I get the "File is being used by another process" error.
So it would seem I need to close the file after I create it? I don't see how to do this though, but it is probably something very simple. I'll post some code but its not really necessary, I'm just using a vanilla flavored string builder and stream writer.
Private Sub createFileLocations()
If Not Directory.Exists("./Path") Then
Directory.CreateDirectory("./Path")
End If
If clsGeneralSettings.Printer1 IsNot Nothing Then
If Not File.Exists("./Path/File1" & ".txt") Then
File.Create("./Path/File1" & ".txt")
End If
End If
End Sub
Private Sub AppendTextFile(randomId As String, PrintDate As Date, PrintName As String)
Try
Dim _stringBuilder As StringBuilder = New StringBuilder
Dim _StreamWriter As StreamWriter
Dim fileName As String
If PrintName = clsGeneralSettings.Printer1 Then
fileName = "./Path/File1" & ".txt"
qPrinter1.Enqueue(randomId)
If qPrinter1.Count > 10 Then
qPrinter1.Dequeue()
End If
_stringBuilder.AppendLine(PrintDate + " | " + randomId)
_StreamWriter = New StreamWriter(fileName, True)
End If
'Todo: Figure this out
Using _StreamWriter
_StreamWriter.Write(_stringBuilder.ToString)
_StreamWriter.Flush()
_StreamWriter.Close()
_stringBuilder.Clear()
End Using
Catch ex As Exception
End Try
End Sub