Search code examples
c#file-existsgetfiles

Check if multiple files exist from using Get Files and if they do exist then copy


I currently have 2 folders on my desktop "START" and "END". There could be any number of files in start folder but I need to figure out the following.

If the filenames exist in the START FOLDER then check if they exist in the END Folder and if they do COPY the files that exist.

I have stated the strings in the code and have used GetFiles to find the file names in each folder. But cant piece it together ...

var USERNAME = Environment.UserName;
        string START_DIRECTORY = @"C:\Users\" + USERNAME + "\\Desktop\\START";
        string END_FOLDER_STRING = @"C:\Users\" + USERNAME + "\\Desktop\\END";
        string[] files = System.IO.Directory.GetFiles(START_DIRECTORY);
        string[] files2 = System.IO.Directory.GetFiles(END_FOLDER_STRING);

Solution

  • The simplest thing: iterate over every file in START_DIRECTORY and check if a correcposing file exists in end files. If it does, copy it. Beware that performacewise this is not the best solution

    static void Main(string[] args)
    {
        var USERNAME = Environment.UserName;
        string START_DIRECTORY = @"C:\Users\" + USERNAME + "\\Desktop\\START";
        string END_FOLDER_STRING = @"C:\Users\" + USERNAME + "\\Desktop\\END";
        string[] startFiles = System.IO.Directory.GetFiles(START_DIRECTORY);
        string[] endFiles = System.IO.Directory.GetFiles(END_FOLDER_STRING);
    
        //for every file in start files
        foreach (var startFile in startFiles)
        {
            //get its name
            var startFileName = Path.GetFileName(startFile);
            //and try to get a file with the same name in end file
            var correspondingFineInEndFiles = endFiles.FirstOrDefault(endfile => Path.GetFileName(endfile) == startFileName);
            //if the file in end file does exist
            if (correspondingFineInEndFiles != null)
            {
                //copy it, and override the old file
                File.Copy(startFile, correspondingFineInEndFiles, true);
            }
        }
    }