我有一个应用程序,如果文件不存在,它会创建一个文本文件,然后向其中写入一些内容。当我创建并立即写入文件时,它在第一次运行时效果很好。我的问题是,下次执行此代码并且文件已创建时,当我尝试写入文件时会引发异常。我收到“另一个进程正在使用文件”错误。
所以看起来我需要在创建文件后关闭它?我不知道如何做到这一点,但这可能非常简单。我会发布一些代码,但它并不是真正必要的,我只是使用 Vanilla flavor 的字符串构建器和流编写器。
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
关于.net - File.Create() 之后的 "File is being used by another process",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19705468/