c# copying files from source folder to target folder

user235973457 picture user235973457 · Aug 2, 2013 · Viewed 16k times · Source

Source and Target have the same subdirectories like this :

c:\fs\source\a\
c:\fs\source\b\

c:\fs\target\a\
c:\fs\target\b\

I am battling with copying files from source to target if not existing files. What is the best way in C# to compare source folders with target folders - check if target files dont exit, copy files from a specific source (c:\fs\source\a\config.xml and app.config) to a specific target (c:\fs\target\a\). If target files exist, ignore it. How to write it in C#?

Your code example very much appreciated. Thanks!

    public void TargetFileCreate()
    {
        foreach (var folder in SourceFolders)
        {
            string[] _sourceFileEntries = Directory.GetFiles(folder);

            foreach (var fileName in _sourceFileEntries)
            {    //dont know how to implement here:
                 //how to compare source file to target file to check if files exist or not
                 //c:\fs\source\A\config.xml compares to c:\fs\target\A\ (no files) that should be pasted
                 //c:\fs\source\B\config.xml compares to c:\fs\target\B\config.xml that is already existed - no paste
            }
        }
    }

Answer

Damith picture Damith · Aug 2, 2013
foreach (var file in Directory.GetFiles(source))
{
    File.Copy(file, Path.Combine(target, Path.GetFileName(file)), false);
}