app still holds on to file?

Eduardo Lorenzo

Well-known member
Joined
Jun 27, 2006
Messages
86
Hi everybody. Am using asp.net and am developing a site that handles data.

Part of the functionality is to create a text file on the server (triggered and populated with values from the client) as part of daily report/s and validation. (the text file will be used to compare with the crystal reports values and and values from the table to see if all transactions were recorded properly)

right now I have this:

Code:
Dim Writer1 As New IO.StreamWriter("C:\serverpathgoeshere\machinegeneratedfilename.txt")
            For ctr As Int16 = 0 To myds.Tables(0).Rows.Count - 1
                addContents(myds.Tables(0).Rows(ctr)("accountno"), 20)
                more lines go here
                Writer1.Write(payfilecontents & Environment.NewLine)
                payfilecontents = ""
            Next
            Writer1.Close()

addcontents is a function that builds a line of text and saves it as payfilecontents <- a string variable

my problem is this:
THe file is generated and populated. But when I try to delete the file using windows explorer (because I am still testing) windows gives me an error that an application is still attached/using the file even when my application has already redirected back to a previous page.

help.
 
Perhaps this block of code throws an exception and never actually calls the Writer1.Close line?

Generally, when I write code that uses a StreamWriter I always enclose it in a try...catch...finally block. The snippet would look like:

Code:
Dim sw as StreamWriter = nothing
Try
   sw = new StreamWriter(fineName)
    ...   
Catch ex As Exception or a specific exception if you have specific things you need to do, or no catch if you dont care
   MessageBox.Show(ex.message)
Finally
   If not sw is nothing Then
      sw.Close
   End If

   sw = nothing
End Try
That finally ensures that no matter what happens, the StreamWriter will get closed.
 
very basic but I think it will work..

although this can of course guarantee that the streamwriter will close.. what really bugs me is what kept it open in the first place? :confused:

thank you very much for the reply.. I have added it to my code.
 
Back
Top