Solved

File is in use and will not allow any updating in vb.net

Posted on 2014-02-04
17
177 Views
Last Modified: 2014-02-06
I am trying to update an .xml file that has already been previously created. When I call my delete command because I want to delete the file and then recreated it with the updated information. I get an error that the fil
   'members
    Public PartfileData As New RequestedDataCollection()
    Public FileHeader As New FileHeader

    'Save - saves the part file to a file
    Public Sub Save(ByVal filename As String)
        Try
            'do we need to delete the file
            Dim info As New FileInfo(filename)
            If info.Exists Then
                info.Delete()
            End If
            'create the new file
            Dim stream As New FileStream(filename, FileMode.Create)
            'save it
            Dim serializer As New XmlSerializer(Me.GetType)
            serializer.Serialize(stream, Me)
            'close the file
            stream.Close()
        Catch ex As Exception

        End Try
    End Sub

Open in new window

e in is use.
0
Comment
Question by:cmdolcet
17 Comments
 
LVL 15

Expert Comment

by:unknown_routine
ID: 39832962
Here:
'do we need to delete the file
            Dim info As New FileInfo(filename)
            If info.Exists Then
                info.Delete()
            End If

You s[specify  a filename. Are you sure thus file is not in use?

Can you delete this file manually?
0
 
LVL 40
ID: 39833000
On which line do you get the error.

If it is on Delete, then the file is probably in use by some other process. Otherwise...

The Delete is useless anyway. When you call the FileStream constructor with FileMode.Create, the file is overwritten if it already exists.

Also, when you need to delete only one file, do not create a FileInfo object. Simply use the static method

     File.Delete(filename)

When you create a FileInfo object, the object might hold the file handle even after the file is deleted, and that might cause your problem. File.Delete simply deletes the file without creating an object and is usually a better way to delete a file.
0
 

Author Comment

by:cmdolcet
ID: 39833072
I get the error on the info.delete line.

If I follow your logic and do a file.Delete(filename) I still get an IOException was unhandled
error "The process cannot access the file because it is being used by another process"
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 40
ID: 39833129
The file is either opened by another process or was not closed properly the last time it was written to.

The problem might be cause by your inneficient error Handler. If there is a problem while writing to the file, the execution will jump to the end of the method and will skip the stream.Close line. This could have happened before, and the file handle is stuck in the garbage collector.

If so, restarting the computer should release the file and you should be able to go on.

As for the proper handling, you should do the following:
      Try
            'do we need to delete the file
            Dim info As New FileInfo(filename)
            If info.Exists Then
                info.Delete()
            End If
            'create the new file
            Dim stream As New FileStream(filename, FileMode.Create)
            'save it
            Dim serializer As New XmlSerializer(Me.GetType)
            serializer.Serialize(stream, Me)
            'close the file
            ' Move this to the Finally stream.Close()
        Catch ex As Exception

        Finally
            'close the file
            If stream IsNot Nothing Then
                  stream.Close()
            End If

        End Try
    End Sub 

Open in new window

The Finally portion of a Try...End Try is executed whether there is an exception or not, so you are sure that the Stream will be closed properly no matter what.
0
 

Author Comment

by:cmdolcet
ID: 39833429
When I move the stream command down in the Finally catch block I get an error "Stream is a type and cannot be used as an expression.
0
 
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 300 total points
ID: 39833470
Sorry, I should have tested my code in Visual Studio. You need to move the declaration of the variable before the Try when you use it in a Finally:
		Dim stream As FileStream

		Try
			'create the new file
			stream = New FileStream(filename, FileMode.Create)
			'save it
			Dim serializer As New XmlSerializer(Me.GetType)
			serializer.Serialize(stream, Me)
		Catch ex As Exception

		Finally
			'close the file
			If Stream IsNot Nothing Then
				Stream.Close()
			End If

		End Try

Open in new window

0
 

Author Comment

by:cmdolcet
ID: 39833528
Does the code work for you? I am still getting that the stream is being used before it is being declared????
0
 
LVL 40
ID: 39833645
Yes, the code works.

You might get a warning (green wavy line), but its not important, the code compiles and runs correctly.

The warning is only because the compiler does not see that I check to make sure that stream is indeed initialized. You could end up with an empty stream if the call to the constructor did not work.

Do you get the error when you compile or when you run? If when running, on which line do you get it?
0
 

Author Comment

by:cmdolcet
ID: 39833727
I get the green line yes and it is not an error, however the code above you added as reference does nothing if it is caught in the Finally Catch it never goes in to close the Stream.
0
 
LVL 40
ID: 39833815
Do you have my exact code? If you did not remove the Close that you had first, then when everything works well, the file is already closed when you get into the finally.

Show me the code that you have now.
0
 

Author Comment

by:cmdolcet
ID: 39833850
 'Save - saves the part file to a file
    Public Sub Save(ByVal filename As String)
        Dim stream As FileStream
        Try
            'do we need to delete the file
            'Dim info As New FileInfo(filename)
            'If info.Exists Then
            '    info.Delete()
            'End If

            'File.Delete(filename)
            'create the new file
            'Dim stream As New FileStream(filename, FileMode.Create)
            stream = New FileStream(filename, FileMode.Create)
            'save it
            Dim serializer As New XmlSerializer(Me.GetType)
            serializer.Serialize(stream, Me)
            'close the file
            stream.Close()
        Catch ex As Exception
        Finally
            If stream IsNot Nothing Then
                stream.Close()
            End If

        End Try
    End Sub

Open in new window

0
 
LVL 40

Accepted Solution

by:
Jacques Bourgeois (James Burger) earned 300 total points
ID: 39834116
I have run your code, and the Stream.close in the Finally does get a hit.

The Close just before the catch is not necessary, because Finally is triggered no matter if there is an exception or not. But adding it or removing it does not change anything. I have checked your last piece of code, and the Close in the Finally gets executed everytime here.


You should never have a Catch with nothing in it. If an error occurs, you do not see it. I suspect that this is what is happening here. There might be a problem creating the Stream (invalid filename, security, etc.). Thus the stream is not initialized, triggers an exception, goes to the finally, where it is Nothing and then skips the Close.

Have you tried running the code step by step to see what it is doing and if Stream does get initialized when you call its constructor?
0
 

Author Comment

by:cmdolcet
ID: 39835507
Yes I have and when it goes into the catch statement the stream never gets initialized.
0
 
LVL 40
ID: 39836120
What is the value of the Message property in ex when you go in the Catch. This should tell you why the Stream is not instanciated.
0
 

Author Comment

by:cmdolcet
ID: 39836414
The process cannot access the file because it is being used by another process.
0
 
LVL 40
ID: 39836488
Reboot your computer. This should release the file.

Do nothing but go in Visual Studio, open your project, put a breakpoint at the beginning of the Sub.

Start the program. When it hits the breakpoint, execute the code step by step (F10).

If you still get the same error message on the first pass, then something opens you file and does not close it before you get to that point. It can be another program that starts automatically when you launch Windows, but it can also be another method that runs before that one in your application.

If everything goes through up to the close, then continue executing step by step up to the End Sub. Once there, grab the yellow Arrow in the margin with your mouse, and drag it back at the first Dim at the beginning of the Sub.

Go again with the step by step. If all goes well, then your method is OK. There might be another method in your application that runs after this one, opens the file and does not close it.

If it worked up to the Close on the first pass but then gives you an error after you dragged the yellow Arrow and then gives you the error on the second pass, then my more than 12 years of experience in .NET are useless.
0
 
LVL 27

Expert Comment

by:Ark
ID: 39838338
Just courious - why do you deleting file since you specify FileMode.Create?
Public Const Create As System.IO.FileMode = 2
     Member of System.IO.FileMode
Summary:
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question