Solved

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

Posted on 2012-04-11
9
267 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 167 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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
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 166 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 167 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

Technology Partners: 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!

Question has a verified solution.

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

Suggested Solutions

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

738 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