• 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

    • I happen to try it today not knowing about the update and was happily surprised; it is great.
    • Hello, Hardware Support Applications are a special kind of Microsoft Store app and have to go through additional checks and certifications because they can communicate directly with their driver, which means that a vulnerability in one of them could allow an attacker access to kernel space memory through the HSA ←→ device driver interface.  In other words, a BYOVD (bring your won vulnerable driver) attack, but with the HSA being used as an extra step. Remember, the Microsoft Store is strategic to Microsoft's long-term goals: they see it as the means to get the same 30% of every application sale that Apple and Google get through their stores, which is why it has been a fixture of Windows since Windows 8 was introduced in 2012 despite a low adoption rate.  Microsoft cannot afford to have anyone get an app through their store which causes a security issue for their end users.  Even if the app was written by and uploaded to the Microsoft Store by a partner, it is Microsoft's name on the store, and they are the ones that will have reputational/brand damage if they allow something malicious into their store. Regards, Aryeh Goretsky  
    • This is more from my childhood, when nickelodeon just launched and had to license shows to have something to air. Left a big an impact, but probably more emotion positive / childhood thing. Europe got the follow up season's decade's latter with the animation studio that did Air Bender but never licenses for the US. I miss the day's of longer intro's. Nier (PS3) Intro is epic, and was very unexpected.  PS1 Xengears was also epic and an amazing game.  
    • Sayan Sen, do you think one day an image of the Windows Vista desktop or the wallpaper could be used in the primary image of an article? (When I think of CDs and DVDs I think of that release of Windows and of earlier releases; it is the one that debuted IMAPI 2.0 and other features.)
    • Big fan of EAC Here's a good non-default naming scheme I found on the web (can't take credit) File Name Scheme - %albumartist%\%year% - %albumtitle%\%tracknr2% %title% Various Artists Naming Scheme - Various Artists\%year% - %albumtitle%\%tracknr2% %title% Also, I need test but there is a new flac.exe binary & dll you can drop in the folder to upgrade flac support. I did this pre EAC 1.8. EAC 1.8 did upgrade it to 1.4.3. Flac 1.5.0 came out this year. https://ftp.osuosl.org/pub/xiph/releases/flac/ I don't know how much of a difference / impact will make.
  • Recent Achievements

    • Week One Done
      Ricky Chan earned a badge
      Week One Done
    • Week One Done
      maimutza earned a badge
      Week One Done
    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      484
    2. 2
      +FloatingFatMan
      263
    3. 3
      snowy owl
      240
    4. 4
      ATLien_0
      227
    5. 5
      Edouard
      188
  • Tell a friend

    Love Neowin? Tell a friend!