7

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
4

4 回答 4

15

有问题的代码/行是这个

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
于 2013-10-31T11:39:39.583 回答
3

您可以消除您拥有的文件创建逻辑并让 StreamWriter 创建文件。

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

于 2013-10-31T11:47:44.137 回答
2

看看文档

此方法创建的 FileStream 对象的默认 FileShare 值为 None;在关闭原始文件句柄之前,没有其他进程或代码可以访问创建的文件。

File.Create()运行该方法后,您有一个打开的 FileStream 句柄。

于 2013-10-31T11:41:51.570 回答
-1

您错过了处理一些图像,它可能是当前图像或原始图像,您可以这样做CurrImage.Dispose() & OriginalImage.Dispose()

于 2016-03-21T13:50:59.233 回答