Dot-Net

File.Create() 之後的“文件正在被另一個程序使用”

  • October 26, 2018

我有一個應用程序,如果該文件尚不存在,則創建一個文本文件,然後向其中寫入一些內容。當我創建並立即寫入文件時,它第一次工作得很好。我的問題是,下次執行此程式碼並且文件已經創建時,當我嘗試寫入文件時它會引發異常。我收到“文件正在被另一個程序使用”錯誤。

所以看起來我需要在創建文件後關閉它?我不知道如何做到這一點,但這可能是非常簡單的事情。我會發布一些程式碼,但它並不是真正必要的,我只是使用香草味的字元串建構器和流編寫器。

   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

有問題的程式碼/行是這個

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

File.Create返回一個 FileStream,如果您想稍後寫入該文件,則需要關閉它。將您的程式碼更改為以下內容應該可以解決您的問題。

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

您可以消除您擁有的文件創建邏輯並讓 StreamWriter 創建文件。

http://msdn.microsoft.com/en-us/library/36b035cb%28v=vs.110%29.aspx

引用自:https://stackoverflow.com/questions/19705468