Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am using AsParallel to iterate through a list files in a directory to copy them to some other location, after which when I try to delete them I am getting file access error saying it is being using by another process.

Can someone tell where it is causing the issue.

What I have tried:

C#
command.OutputDirectory
                    .GetFilesWhere(source => source.Extension.In(command.OutputExtensions))
                    .AsParallel()
                    .ForEach(source =>
                    {
                        Logger.LogInfo(@"Copying [{0}] to [{1}]...".FormatWith(source.FullName, OutputDirectory));
                        source.CopyTo(OutputDirectory.PathCombine(source.Name), true);                        
                        try
                        {
                             source.Delete();
                        }
                        catch (Exception e)
                        {
                            Logger.LogError("Exception while deleting the output file: " + e.Message);
                        }
                    }
                    );
Posted
Updated 25-Oct-17 20:58pm
v3
Comments
Ramana Bellary 26-Oct-17 5:11am    
My doubt is if the source.CopyTo is still holding the reference to the file.
Or is it caused because of using AsParallel !!!

1 solution

The error message tells you what the problem is:
I am getting file access error saying it is being using by another process

The file is in use: it is open and as a result locked.

Somewhere - probably elsewhere in your code - you have opened the file (probably for write access, but it could be read) and not closed the stream that you opened. Until that stream is closed, the file is locked and cannot be reopened for writing or deleted.

So go through your code with a fine tooth comb: look at everywhere you reference that file, and follow it until you close the stream. If you don't close it, you can't delete it - so when you are finished with the file, close and dispose the objects you used to access it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900