"File is being used by another process" after File.Create()

Brandon picture Brandon · Oct 31, 2013 · Viewed 19.9k times · Source

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

Answer

Jehof picture Jehof · Oct 31, 2013

The problematic code/line is this

If Not File.Exists("./PalletQueue/Printer1" & ".txt") Then
  File.Create("./PalletQueue/Printer1" & ".txt")
End If

File.Create returns a FileStream, that you need to close, if you want to write later to that file. Changing your code to the following should solve your problem.

If Not File.Exists("./PalletQueue/Printer1" & ".txt") Then
  Dim file as FileStream = File.Create("./PalletQueue/Printer1" & ".txt")
  file.Close()
End If