Home > database >  file copy only if the names are not same
file copy only if the names are not same

Time:09-28

I've written a piece of code to copy a file from one place to another. Before that I want to check whether the file names are not same for the files which exist in the source and destination. If exists remove that file.

For that purpose I've written the below piece of code. Here once it find the files with the same name, the next loop fails.

This is the error 'Collection was modified; enumeration operation may not execute.'

Kindly someone help me with this part

var directory = new DirectoryInfo(@"\\Shared\Log\Testing\");
var files = (from f in directory.GetFiles()
                where f.CreationTime >= fromdate && f.CreationTime <= todate
                select f).ToList();

var localdirectory = new DirectoryInfo(@"C:\Users\Desktop\Test\");
var localfiles = (from f in localdirectory.GetFiles()
                    select f).ToList();

foreach (var file in files)
{
    foreach (var localfile in localfiles)
    {
        if (file.Name == localfile.Name)
        {
            files.Remove(file);
            Console.WriteLine(file.Name   "- File already exists");
        }
    }
}

CodePudding user response:

Instead of removing file from the shared directory, just filter the list and then perform the copy operation,

//UniqueFiles contains all files that are not present in the localFiles.
var uniqueFiles = files
       .Where(x => !localfiles.Any(localFile => localFile.Name == x.Name));

Why you are getting error "'Collection was modified; enumeration operation may not execute.'"?

  • You are iterating over files(first foreach loop) and inside if condition you are trying to remove one file from the files list.
  • files.Remove(file); removing file from the list, this is modifying the enumerable.
  • C# does not support iterating over the enumerable which is changing within it, it throughs above error
  • Related