Solved

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

Posted on 2012-04-11
9
264 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
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 85

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
 
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
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.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

920 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

18 Experts available now in Live!

Get 1:1 Help Now