greatWallace
greatWallace

Reputation: 37

Copy files containing a name from source to destination c#

I have a list of Strings with a series of names, I want to find these names in the source directory and copy them to the destination.

This is what I am trying but with this I copy all source directory in target directory:

        List<string> ncs = new List<string>();
            ncs = getNames();

        foreach (var file in Directory.GetFiles(sourceDir))
             File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));


        foreach (var directory in Directory.GetDirectories(sourceDir))
            CopyNCfromTo(directory, Path.Combine(targetDir, Path.GetFileName(directory)));

I am trying in this way too:

List<string> ncs = new List<string>();
            ncs = getNames();
            for (int i = 0; i < ncs.Count; i++)
                {
                  FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles(ncs[i].ToString());
                }

I thought to loop the list and the look for every file in the source folder, how could I do this?

Upvotes: 0

Views: 1099

Answers (3)

Crowcoder
Crowcoder

Reputation: 11514

You can iterate over ncs, build the source and destination paths, and do a copy if the file exists.

Caveat: File.Exists() can introduce a race condition. If you are not confident no other process is working in that folder then you should handle IO exceptions.

string sourceDir = "C:\\....";
string targetDir = "C:\\....";

foreach (string filename in ncs)
{
    string srcFile = Path.Combine(sourceDir, filename);
    string destFile = Path.Combine(targetDir, filename);

    if (File.Exists(srcFile))
    {
        File.Copy(srcFile, destFile);   
    }   
}

Upvotes: 1

Wiliam Paulino
Wiliam Paulino

Reputation: 101

This is happening because foreach is browsing the files contained in the folder and not the list of names, that way, all files are copied to the destination folder.

foreach(string fileName in ncs){
    string path = sourceDir + fileName;
    bool result = System.IO.File.Exists(path);
    if(result == true){
         string destinationPath = targetDir + fileName;
         System.IO.File.Copy(path,destinationPath);
    }
}

That way you go through the list of names and check if the file exists, if it exists, copy the file to the destination folder

Upvotes: 1

anilcemsimsek
anilcemsimsek

Reputation: 814

I assume that the ncs list containing only names not the file path or the file name with extension.

     foreach (var file in Directory.GetFiles(sourceDir))
            if (ncs.Contains(Path.GetFileName(file).Split('.').First()))
                File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));

Upvotes: 2

Related Questions