Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 193
  • Last Modified:

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

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
cmdolcet
Asked:
cmdolcet
2 Solutions
 
unknown_routineCommented:
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
 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
cmdolcetAuthor Commented:
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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
cmdolcetAuthor Commented:
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
 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
cmdolcetAuthor Commented:
Does the code work for you? I am still getting that the stream is being used before it is being declared????
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
cmdolcetAuthor Commented:
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
 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
cmdolcetAuthor Commented:
 '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
 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
cmdolcetAuthor Commented:
Yes I have and when it goes into the catch statement the stream never gets initialized.
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
cmdolcetAuthor Commented:
The process cannot access the file because it is being used by another process.
0
 
Jacques Bourgeois (James Burger)PresidentCommented:
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
 
ArkCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now