Re: Application not letting go of file.
- From: "Michel Posseth [MCP]" <MSDN@xxxxxxxxxxx>
- Date: Sat, 28 Jun 2008 09:45:45 +0200
Phill it wil also take care of the Explicitly initialise variable nag
warning of VS
Nowadays i code all my constructs like this as it
1. doesn`t give you the nag warnings and thus the need to set a nohing /
empty pointer
2. it is shorter to type
3. gives you extra scope in long routines ( variabels declared in using
blocks are only in scope within the using block )
4. it takes care of cleanup
5. it just looks nicer to me
Try
using fs As FileStream = File.OpenRead( path )
using sr As StreamReader = New StreamReader( fs )
end using
end using
Catch ex as Exception
End Try
regards
Michel
"Phill W." <p-.-a-.-w-a-r-d-@xxxxxxxxxxxxxxxxxxxx> schreef in bericht
news:g42dmk$hsu$1@xxxxxxxxxxxxxxxxxxxx
Andrew Cooper wrote:
This is a classic VB "Proper" Developers' misunderstanding - I've done it
myself once or twice ;-)
Setting Object [Reference] Variables to Nothing /rarely/ has any useful
effect. You're simply telling the run-time:
"I don't care what happens to this object any more. Please get rid of it
(i.e. Garbage Collect it) sometime, if and when you get around to it".
To kill off the "resources" (here, that's your file) that an object is
holding on to, you have to explicitly Dispose of it. Have a read up on
the IDisposable pattern (or Interface).
Revisiting your code:
' Explicitly initialise variable; avoids warnings in VS'2005.
Dim fs As FileStream = Nothing
Dim sr As StreamReader = Nothing
. . .
Try
fs = File.OpenRead( path )
sr = New StreamReader( fs )
. . .
sr.Close() ' implicitly Dispose's the underlying stream
Catch ex as Exception
If Not ( sr Is Nothing ) then
sr.Close()
ElseIf Not ( fs Is Nothing ) then
fs.Dispose()
End If
End Try
You can also use the "Using ... End Using" construct, which implicitly
does the Dispose (coded long-hand above) for you.
HTH,
Phill W.
.
- References:
- Application not letting go of file.
- From: Andrew Cooper
- Re: Application not letting go of file.
- From: Phill W.
- Application not letting go of file.
- Prev by Date: Re: Setup Project - Test If User Is An Administrator?
- Next by Date: Re: Type 'ConnectionStringData' is not defined.
- Previous by thread: Re: Application not letting go of file.
- Next by thread: acrobat distiller
- Index(es):
Relevant Pages
|