• 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

    • It's an improvement overall but I'm also of the idea that they should just give users more options and let them have the menu they like instead of just going with one outline and some minor options (though finally getting rid of recommended is great). I know people who don't want pins and would rather it all be just the list/grid of apps. Others just want pins, others want them side by side and not up on top of each other. Have more layout options and let people mix and match, problem solved.
    • Hi all, I've got a Pioneer VSX 815-k receiver. Love this thing, however, my cat did his business on top of it and kinda recked it... Only analog works (5.1 surround RCA inputs). Normally I'd use toslink from mobo to digital in on the receiver, but the result is a ton of loud white noise over the music. Analog works just fine, so I'm forced to use the 3.5mm jacks on the rear of the mobo to the RCA inputs on the receiver. The issue I face is that there is no DTS or anything fun.. Originally, I could play all my MP3s or watch YouTube etc, and the subwoofer would be booming as I like because of the mixing from the DAC. Now with the analog, none of that is happening  I'm wondering if there's some kind of software solution for Windows to get the subwoofer to play as it did when I had it hooked up through toslink, but for analog out instead. As of now, only audio files that were encoded specifically to produce sound to the sub, will work, but nothing else. As to which onboard sound solution my mobo has, this from the website's description: 121dB SNR AMP-UP Audio with ALC1220 & High-End ESS SABRE 9018 DAC with WIMA audio capacitors Sound BlasterX 720°, the top-of-the-line audio engine solution for 4K gaming and entertainment  yea it uses that wonky SBx 720 app to change the audio effects n stuff.. but doesn't help with my issue Eventually yea, I wanna buy a new one. They're about $80 on ebay after shipping, but that will have to wait.
    • Serious question here. Why is the start menu such a heated topic? I can't remember the last time that I used the start menu for anything at all other than it pops up when I hit the WIN key on my keyboard before I type for the program I want to run and then hit Enter or to restart my machine. I honestly wish it would just go away, and it just be replaced with the PowerToys Run menu. Am I missing something with the Start menu? I see people always talking about installing third party replacements and such, but I just wonder what some are actually using the Start menu for that I might be missing out on. Genuine question. Hopefully not offending anyone as I know everyone has their own way to work and access things in the OS.
    • These are the Apple Watch models that support watchOS 26 by Aditya Tiwari Apple has announced the latest operating system upgrade for its smartwatch lineup, called watchOS 26, not watchOS 12, as many expected a while ago. The Cupertino giant has unified the software experience across its platforms by introducing the "Liquid Glass" software design and renaming all the operating systems to version 26. That said, the next question is which Apple Watch models will support watchOS 26. Apple has shared the official list of devices: Apple Watch Ultra 2 Apple Watch Ultra Apple Watch Series 10 Apple Watch Series 9 Apple Watch Series 8 Apple Watch Series 7 Apple Watch Series 6 Apple Watch SE (2nd Generation) The upcoming Apple Watch update brings several new features to your wrist. Liquid Glass design gives a fresh look to the UI with updated Control Center and translucent buttons within apps. It's new Workout Buddy feature can use an Apple Intelligence-enabled iPhone nearby to provide personalized, spoken motivation during workouts. Building on the Double Tap feature, you can now flick your wrist to perform actions like muting incoming calls, silencing timers, and dismissing notifications when your hands are full. It is available on Apple Watch Ultra 2 and Apple Watch Series 9 (or later). watchOS 26 is currently available for testing through the Apple Developer Program. It will roll out to general users during the fall season, when Apple is expected to refresh the Ultra and SE models. Note that your Apple Watch must be paired with an iPhone 11 (or later) or iPhone SE (2nd generation or later) running iOS 26. While the list of Apple Watch models that support watchOS 26 remains the same, it won't work with iPhone Xs/Xs Max and iPhone Xr, which were previously supported on watchOS 11. You can check out the respective lists of supported devices for iOS 26, iPadOS 26, and macOS 26 Tahoe.
  • Recent Achievements

    • Explorer
      MusicLover2112 went up a rank
      Explorer
    • Dedicated
      MadMung0 earned a badge
      Dedicated
    • Rookie
      CHUNWEI went up a rank
      Rookie
    • Enthusiast
      the420kid went up a rank
      Enthusiast
    • Conversation Starter
      NeoToad777 earned a badge
      Conversation Starter
  • Popular Contributors

    1. 1
      +primortal
      501
    2. 2
      ATLien_0
      268
    3. 3
      +FloatingFatMan
      257
    4. 4
      Edouard
      201
    5. 5
      snowy owl
      170
  • Tell a friend

    Love Neowin? Tell a friend!