Solved

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

Posted on 2014-02-04
17
175 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
Comment Utility
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

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
Comment Utility
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
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Does the code work for you? I am still getting that the stream is being used before it is being declared????
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:cmdolcet
Comment Utility
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

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
Comment Utility
 '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
Comment Utility
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
Comment Utility
Yes I have and when it goes into the catch statement the stream never gets initialized.
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
Comment Utility
The process cannot access the file because it is being used by another process.
0
 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video discusses moving either the default database or any database to a new volume.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now