Issue while closing a StreamWriter

  • Thread starter Thread starter mohit.jha
  • Start date Start date
M

mohit.jha

Iam using streamwriter class of .net to write in a file. The location
of
file is a network drive. Now if for some reason the network is not
there
and I execute
sw.close I get a exception ( that's ok).
But later when network comes and I try to delete this file, it says
that the
file is being used by a process. How to release the file handle in such
a
case.

Thanks,
Mohit
 
Hi

There different ways to do that. Here are two proposal - perhaps others
have any better idea.

1.) You can keep the stream-writer instance as long as you can not
close it correctly in the memory - which means you have to wait until
your network connection is coming back and then you close your
stream-writer in a correct way

2.) Your are copying your file temporarily into a local temp folder,
then you write your stuff and afterwards you replace the network-copy
on the network

Hope this helps
Roland
 
Iam using streamwriter class of .net to write in a file. The location
of
file is a network drive. Now if for some reason the network is not
there
and I execute
sw.close I get a exception ( that's ok).
But later when network comes and I try to delete this file, it says
that the
file is being used by a process. How to release the file handle in such
a
case.

Thanks,
Mohit

The reason you can't delete the file is because the file handle is still in
use at the client side. Only possibility to recover from this, is to pass
the FileStream.Handle to the Win32 API CloseHandle when such exception
occurs, doing so will release the OS file handle so you can re-open or
(better) delete the file.


[ DllImport("Kernel32") ]
public static extern bool CloseHandle(IntPtr handle);
....


FileStream fs;
try {
...
}

catch(IOException)
{
// If resource no longer available, or unable to write to.....
if(...)
CloseHandle(fs.Handle);
}


Willy.
 
Roland said:
Hi

There different ways to do that. Here are two proposal - perhaps others
have any better idea.

1.) You can keep the stream-writer instance as long as you can not
close it correctly in the memory - which means you have to wait until
your network connection is coming back and then you close your
stream-writer in a correct way

You can't do this, when the session with the server recovers all open File
Handle becomes invalid at the server side. Also you should not try to re-use
the file as she will probably be corrupt after a network failure.
 
Back
Top