I have a file copying program and I have a custom class that utilizes a System.IO.FileSteam to copy a file to a destination computer. For the most part it works quite well. However I use it to copy to many remote locations. Some of them have subpar network connections. Every so often I'll get a server that has a unreliable network connection and it will momentarily drop off the network for a few seconds. When this happens my FileStream breaks with the exception "The specified network name is no longer available.". This is expected.
However the problem is after the program has waited 60 seconds it will retry the transfer. The problem now is it can't even start because I get the error "The process cannot access the file '\\MyServer\c$\MyFile.zip' because it is being used by another process". I'll continue to get this error indefinitely until I close the program and restart the transfer, then it is able to transfer once again.
It would appear that my source server still has a file handle open when this happens that's preventing the transfer again and closing the program releases it. I would like to programically release the handle so I can restart the transfer automatically.
Here's what I've tried so far:
When the file transfer is started, I grab the FileSteam.SafeFileHandle to a variable. When I get the above error, I've tried accessing SafeFileHandle.SetHandleAsInvalid(), SafeFileHandle.DangerousRelease() and SafeFileHandle.Close(), but I'll still get the file in use error when I retry.