• 0

FileStream - The Process Cannot Access The File


Question

Hello, 

 

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.

12 answers to this question

Recommended Posts

  • 0

To replicate the problem, I imported my DLL into powershell.  I waited for the problem to occur.  I then grabbed the SafeFileHandle.  I first tried SetFileHandleAsInvalid() then retried.  Then I tried DangerousRelease().  Finally I tried Close(), but at that point I got "Exception calling "Close" with "0" argument(s): "Safe handle has been closed".

 

Also if I just call my handle variable it shows:   IsInvalid:  False, IsClosed:  True

  • 0
  On 13/03/2014 at 21:48, snaphat (Myles Landwehr) said:

Is the filestream locked? Closing a file that has outstanding locks is undefined according to the documentation.

 

Some how I never thought of that.  I always assumed that when I received an exception on a FileStream.Write(...) that the filestream was hosed then.  I adjusted my code as follows:

                try
                { m_Dest.Write(m_Buffer, 0, m_CurrentBlockSize); }
                catch (IOException ex)
                {
                    //  added the section below:
                    if (m_Dest.CanWrite)
                    {
                        try
                        { m_Dest.Close(); }
                        catch { }
                    }
                    // end new section
                    HadExceptionWhileCopying(ex, true);
                    return;
                }

So far it worked in my test environment.  Will see if it works in production tomorrow.

Thanks Myles!

  • 0

^ yeah the filestream may still be valid and be locked. For that matter, it could technically be still not working (in terms of communication), but it could still be marked as locked. I was thinking of calling unlock() when I posted my response. I'm not sure why the above code would work given that canWrite should just give you the state of whether the stream is closed or not and if you call close() on an already closed stream it should work fine.

  • 0
  On 15/03/2014 at 00:06, stumper66 said:

My above solution worked.

 

I dug through my existing code and it was supposed to call a close on the filestream  in the event of an error but due to a flaw in my logic it never got called.

I see, that definitely fits the bill for the error you were getting!

  • 0
  On 15/03/2014 at 00:28, notchinese said:

Is it feasible given the code design to just wrap the filestream in a using() {} block?

 

"using" is an assurance that Dispose() will be called to free resources. It doesn't necessarily call Close(). try...finally would do that.

  • 0
  On 21/03/2014 at 12:54, Eric said:

"using" is an assurance that Dispose() will be called to free resources. It doesn't necessarily call Close(). try...finally would do that.

Yes it does. http://stackoverflow.com/questions/911408/does-stream-dispose-always-call-stream-close-and-stream-flush

 

In general, if an object implements Dispose() then you can expect that calling that is enough to clean it up properly, whatever the state it was in.

 

Also, using actually expands to try-finally so it's strictly equivalent, if all you're doing in the finally clause is to call Dispose().

  • 0
This topic is now closed to further replies.
  • Posts

    • OneDrive for Mac now lets you sync files to removable drives by Taras Buria If you use OneDrive on Mac and often work with external drives (a common sight among Mac users where internal storage is not upgradeable), Microsoft has some good news for you: the OneDrive client for macOS now supports removable drives, allowing you to sync files to external disks, both non-removable and removable. Microsoft introduced external drive support in OneDrive for Mac at the beginning of 2025. However, the initial rollout was limited to drives that macOS detects as non-removable. The company received plenty of feedback from users regarding this change, and it is now addressing the inability to sync files to removable drives. External drive support in OneDrive works the same way as syncing files to internal storage. If you unplug your drive, say, a portable SSD, OneDrive will stop syncing and notify you with an error message (there is a short delay for drives that sporadically disconnect). To resume sync, reconnect your drive and restart OneDrive. If you want to sync OneDrive to an external drive, your drive should be formatted for APFS (Apple File System) and protected by FileVault (read-only, network, and quarantined drives are not supported). Also, you need macOS version 15.0 or newer and OneDrive version 25.097 or newer. For now, external drive support is only available for insiders, but a wider rollout is coming soon. Finally, Microsoft adds that external drive support does not allow moving drives between devices. Therefore, you must set up OneDrive sync again every time you connect your drive to a new Mac. You can read more about external drive support in OneDrive for Mac in a post on the official Tech Community website. In other OneDrive news, check out our recently published guide, which details how to change OneDrive folder colors for extra personalization.
    • I'm here for it! Bill Pullman & Rick Moranis Returning For New ‘Spaceballs’; Keke Palmer Also Set https://deadline.com/2025/06/spaceballs-2-casts-rick-moranis-bill-pullman-keke-palmer-1236431204/ It's gonna be epic! 
    • Lipstick on a data-hungry pig...
    • I really feel like we need a 3rd good phone OS option to compete with Google and Apple.
    • After 40 years we asked what the fans want...... and are making this movie anyway! 
  • Recent Achievements

    • One Month Later
      POR2GAL4EVER earned a badge
      One Month Later
    • One Year In
      Orpheus13 earned a badge
      One Year In
    • One Month Later
      Orpheus13 earned a badge
      One Month Later
    • Week One Done
      Orpheus13 earned a badge
      Week One Done
    • Week One Done
      serfegyed earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      536
    2. 2
      ATLien_0
      260
    3. 3
      +FloatingFatMan
      203
    4. 4
      +Edouard
      168
    5. 5
      Xenon
      124
  • Tell a friend

    Love Neowin? Tell a friend!