• 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

    • There is but look up training videos to do data analysis in Excel v the app they use in libre office? Don't even know the name. Besides we are talking about govt employees. Have you tried explaining command line to a govt employee? Look I respect the people but I know that they could not be bothered with open source
    • Let's see how long this lasts. In the end, it comes down to productivity lost because of workflow disruptions. It's not even a question of "which is better", rather how painful will it be to switch and it's hard enough for a single person to switch - imagine an entire city's bureaucracy. Remember, there are governmental system in the US that are still using 5.25" floppy disks... Having been involved in these kinds of swaps, I can tell you - it's never as easy as the fanbase thinks it is.
    • Right, saw it in the microsoft blog, wasn't mentioned in the article, thanks.
    • Multiple internal and external HDDs from Seagate, Western Digital are now at great prices by Fiza Ali Amazon and Newegg are currently offering substantial discounts on a wide selection of internal and external hard drives from Seagate and Western Digital, with prices reduced across multiple capacities. The 4TB WD Purple Surveillance is a 3.5-inch SATA III drive offering sustained transfer rates of up to 175MB/s. It employs Conventional Magnetic Recording (CMR) with a 256MB cache buffer. The drive operates reliably between 0°C and 65°C and can be stored in temperatures ranging from –40°C to 70°C. Western Digital backs this unit with a three-year limited warranty as well. 4TB WD Purple Surveillance Internal HDD: $84.41 (Amazon US) - 8% off The 6TB WD Blue is also a 3.5-inch internal hard drive that connects via SATA III (6Gb/s) and delivers sustained transfer rates of up to 185MB/s. It spins at 5,400 RPM, employs Conventional Magnetic Recording (CMR) technology, and features a 256MB cache buffer. The drive operates reliably in temperatures from 0°C to 60°C (with safe storage down to –40°C and up to 70°C). It is backed by a two-year limited manufacturer’s warranty. 6TB WD Blue PC Internal HDD: $99.99 (Amazon US) - 17% off The 10TB WD Red Pro NAS drive comes in a 3.5-inch form factor and connects via SATA III (6Gb/s). It sustains transfer speeds of up to 267MB/s thanks to its 7,200 RPM spindle and 512MB cache buffer, and employs Conventional Magnetic Recording (CMR) for reliable multi-drive operation. It operates safely between 0°C and 65°C, can be stored or transported in temperatures from –40°C to 70°C, and is covered by Western Digital’s five-year limited warranty. 10TB WD Red Pro NAS Internal HDD: $237.49 (Amazon US) - 15% off This WD Elements Desktop external hard drive offers a 14TB of storage via a USB 3.0 interface (up to 5Gb/s), using a USB Micro-B connector that is backward-compatible with USB 2.0. It operates reliably between 5°C and 35°C and can be stored in temperatures ranging from –20°C to 65°C. The drive is powered by an external adapter and carries a two-year limited warranty. 14TB WD Elements Desktop External HDD: $199.99 (Amazon US) - 31% off The 16TB Seagate Expansion Desktop external hard drive delivers vast storage capacity in a simple, plug-and-play design. USB 3.0 connectivity provides high-speed data transfer rates. Out of the box, the Expansion Desktop model is recognised automatically by Windows, macOS, and ChromeOS systems. If you wish to use Apple’s Time Machine backup utility, the drive must be reformatted to the HFS+ file system. 16TB Seagate Expansion Desktop External HDD: $229.99 (Newegg) - 30% off The 16TB WD Elements desktop external HDD connects via a USB 3.0 interface using a Micro-B cable (up to 5Gb/s.) The drive features plug-and-play functionality, working straight out of the box with Windows PCs. It operates reliably in ambient temperatures from 5°C to 35°C and can be stored in temperatures ranging from –20°C to 65°C. The drive comes with a 2-year limited warranty as well. 16TB WD Elements Desktop External HDD: $249.99 + $20 off promo code SAAET2384 = 229.99 (Newegg) The 16TB Seagate BarraCuda 3.5-inch internal HDD offers Multi-Tier Caching Technology (MTC) which balances NAND flash, DRAM, and media cache layers to accelerate application launches, reduce load times, and maintain consistently high sustained read/write speeds. The included Seagate DiscWizard software simplifies drive migration, cloning, partitioning, and backup tasks. The drive is covered by a two-year limited warranty. 16TB Seagate BarraCuda Internal HDD: $194.99 (Newegg) - 7% off The 20TB Seagate Exos X20 delivers an enterprise-class solution for high-density storage environments and data centres. It offers a sustained sequential transfer rate of up to 285MB/s and advanced caching to ensure low-latency, repeatable response times for data-intensive workloads. It further features 550TB/year workload rating, 2.5 million-hour mean time between failures (MTBF), and five-year limited warranty. PowerChoice and PowerBalance technologies allow administrators to tailor power consumption profiles for active and idle states, reducing energy costs and cooling requirements. Hardware-based AES-256 encryption, password protection, and Seagate Secure certification safeguard sensitive data. 20TB Seagate Exos X20 Internal HDD: $379 + $50 off promo code EPET2523 = $329.99 (Newegg) This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • It's all 1Password's fault for using it before anyone else. 🙃
  • Recent Achievements

    • Collaborator
      Mighty Pen went up a rank
      Collaborator
    • Week One Done
      emptyother earned a badge
      Week One Done
    • Week One Done
      DarkWun earned a badge
      Week One Done
    • Very Popular
      valkyr09 earned a badge
      Very Popular
    • Week One Done
      suprememobiles earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      569
    2. 2
      +FloatingFatMan
      180
    3. 3
      ATLien_0
      175
    4. 4
      Xenon
      116
    5. 5
      Som
      110
  • Tell a friend

    Love Neowin? Tell a friend!