Go Premium for a chance to win a PS4. Enter to Win

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
?
272 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 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

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

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

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Screencast - Getting to Know the Pipeline
Suggested Courses

972 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