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

4

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
Modernistic answered 31/10, 2013 at 11:36 Comment(5)
ok you didnt need to remove the C# tag, .Net is .Net and if someone gives me the answer for C# i can translate it to vb. There is 10x more people with C# tag favorited than the vb.net oneModernistic
Duplicate of System.IO.File.Create locking a file.Carbrey
OK. You are free to add it again if you wish; although you should have specified this in your question (accept both VB.NET and C# answrs). In any case, I am sure that any VB.NET problem can be solved perfectly by the guys coming to the VB.NET tag. Actually your problem is not too difficult...Prevost
BTW you don't even need to use File.Create. StreamWriter takes care of any eventuality (file present or not). BTW2 inside the Using statement you don't need to use .Flush or .Close; Using takes care of all the "disposing actions".Prevost
Thank you, much more helpfulModernistic
G
16

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
Goneness answered 31/10, 2013 at 11:39 Comment(4)
I originally had File.CreateText() but that "Creates and Opens a file" Whereas Create seemingly just "Creates a file" - Was I on the correct track earlier?Modernistic
@BrandonJ Create also creates a file and opens a stream to that file to write intoGoneness
"File.Create returns a FileStream, that you need to close". This is same for c#Dearman
the more you know! Thank you, worked perfectlyOsteophyte
L
3

You could eliminate the file create logic you have and let the StreamWriter create the file.

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

Leading answered 31/10, 2013 at 11:47 Comment(0)
C
2

Have a look at the documentation:

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

You have an open handle to the FileStream after running the File.Create() method.

Countess answered 31/10, 2013 at 11:41 Comment(0)
D
-1

You have missed to dispose some image it may be current image or original image you can do this like CurrImage.Dispose() & OriginalImage.Dispose()

Donnelldonnelly answered 21/3, 2016 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.