Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

The Process Cannot Access The File 'XXX' Because it is being used by another process

Posted on 2012-04-11
9
Medium Priority
?
270 Views
Last Modified: 2012-04-16
Hi EE,
    I have a loop to create same file name with different contents then sending out to a bunch of receivers. I have code like this (both NewCopy/FileToCopy are string variables and stores the path of the file)
 
If System.IO.File.Exists(NewCopy) = True Then
                        System.IO.File.Delete(NewCopy)          'Delete existing 
                        System.IO.File.Copy(FileToCopy, NewCopy, True)

Open in new window


When I run the code, first email sent out just fine but when it comes to the next, above error throws out, anyone have any suggestions how do i take care of this issue? I tried googled a bit, looks like it is not disposed properly, but how should i do that? there's no IO.File.Dispose?
0
Comment
Question by:miketonny
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 37835604
It may simply be that you are attempting to work with the file too quickly.  The operating system itself may take a second or two to release the file.  One possible solution is trap the error in a try/catch, Sleep() for a second, and then try again.
0
 
LVL 2

Author Comment

by:miketonny
ID: 37835646
thx Idle_Mine, I did have a sleeping 1 sec code after this. and same error popped out again. I'll try adding more time into the sleeping see how it goes
0
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 668 total points
ID: 37835658
Some times you have to loop around several times until the file is released.  I'd place a time, or number of re-attempts, limit on the loop though so it doesn't get stuck indefinitely.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Author Comment

by:miketonny
ID: 37835846
I tested further by looping 20 times of this command and a 10sec delay on every loop.
Failed from second loop all the way to last. I tried open up the file during the loop says it's been locked, is there a way i can dispose or close it ?
0
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 664 total points
ID: 37836301
This is the one that i used to see if file test1.xml exists, if yes then delete the file. Next copy the contents of test.xml to test1.xml_

for (var i = 0; i < 10; i++)
                {
                    var di = new DirectoryInfo(Directory.GetCurrentDirectory());
                    var fInfo = di.GetFiles("*.xml", SearchOption.AllDirectories);

                    var fCopy = fInfo.FirstOrDefault(f => f.Name == "test1.xml");
                    if (fCopy != null) fCopy.Delete();

                    var fExisting = fInfo.FirstOrDefault(f => f.Name == "test.xml");
                    if (fExisting != null) fExisting.CopyTo(Directory.GetCurrentDirectory() + @"\test1.xml");

                    Console.WriteLine("{0}. File Copied", i + 1);
                }

Open in new window

0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 668 total points
ID: 37839422
If you are generating this file temporarily then one option is to generate temp file for each loop iteration and save the file name to a list. At the end, pass this list to another thread which keeps trying to delete these files (most will be released by that time anyway) in the background.
0
 
LVL 2

Author Comment

by:miketonny
ID: 37840327
Thx Buggycoder, i tried your code same error popped out on second loop. I have code like below
      Dim di As New System.IO.DirectoryInfo("V:\Database\Export\")
        Dim finfo = di.GetFiles(newCopy.Replace("V:\Database\Export\", ""), IO.SearchOption.TopDirectoryOnly)
        Dim fCopySource = di.GetFiles(fileToCopy.Replace("V:\Database\Export\", ""), IO.SearchOption.TopDirectoryOnly)
        Dim fCopy = finfo.FirstOrDefault()
        If fCopy IsNot Nothing Then
            fCopy.Delete()
        End If

        Dim fExisting = fCopySource.FirstOrDefault()
        If fExisting IsNot Nothing Then
            fExisting.CopyTo(newCopy)
        End If

Open in new window


CodeCruiser, I actually do want to keep an physical copy on the disk so that i can check the content if i want to.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 37853670
>I actually do want to keep an physical copy on the disk so that i can check the content if i want to.

Not sure what you mean. You are trying to delete a file right?
0
 
LVL 2

Author Comment

by:miketonny
ID: 37853719
thanks guys, I have found the solution to my issue, turns out the problem is my 'Mailmessage' needs to dispose/release the attachment resource or it'll keep popping up this error message.
Thank you for all your time in this case I'll distribute the points evenly :)
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question