Solved

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

Posted on 2012-04-11
9
261 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
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
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
Comment Utility
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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 167 total points
Comment Utility
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
 
LVL 2

Author Comment

by:miketonny
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 166 total points
Comment Utility
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 167 total points
Comment Utility
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
Comment Utility
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
Comment Utility
>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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now