-1

I have a .csv file that contains file names and I need to find in a directory the files that match the file names in the .csv and copy them to another directory.

I don`t know how to do this?

.csv file contains:

11420511800.png
11455010100.png
11455010120.png
11455010140.png
11455010150.png
11455010200.png
11455010250.png
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 2
    What have you tried and what is not working for you? Also what exactly you don't know how to achieve? How to open a file? How to read a csv? How to move file? – Guru Stron Jul 24 '21 at 21:54
  • @Guru Stron, i got the file names in a .csv file, but i don`t know how to match the file names with the ones in a directory and if there is a match to copy all files in a new directory. – Daniel Tou Jul 25 '21 at 08:53
  • @Heretic Monkey, it helps a bit. – Daniel Tou Jul 25 '21 at 08:54
  • I would suggest to look into [this](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.exists?view=net-5.0) method for starters. – Guru Stron Jul 25 '21 at 09:00
  • @GuruStron I will look into it, i need to. This was urgent for me and didn`t had time to study, test. – Daniel Tou Jul 25 '21 at 09:59

2 Answers2

0

Directory.GetFiles(@"c:\MyDir\")

That command gets you all the files in a Directory (as a List).

You can iterate through that list and compare it with the names in your .csv file (if you have them in a list [or something similar] too).

h0p3zZ
  • 690
  • 3
  • 16
0
var allowedFiles = File.ReadAllLines(@"X:\your-csv-path-goes-here.csv");
var filesToCopy = new DirectoryInfo(@"Y:\your-source-directory").GetFiles()
                 .Where(f => allowedFiles.Any(af => f.Name.Equals(af, StringComparison.OrdinalIgnoreCase)));
foreach (var fileInfo in filesToCopy) {
   var destFilePath = Path.Combine("Z:\your-destination-directory", fileInfo.Name);
   fileInfo.CopyTo(destFilePath, true); //true => overwrite existing files
}
lidqy
  • 1,891
  • 1
  • 9
  • 11
  • This is what i need but i get an IO exception: "System.IO.IOException was unhandled HResult=5 Message=The target file "C:\Users\touda\OneDrive\Shopia\Proiecte\PRB Shop SRL\Fisiere produse\Imagini produse\img site" is a directory, not a file." – Daniel Tou Jul 25 '21 at 08:56
  • `StringComparison.OrdinalIgnoreCase`what if code is running on Linux? – Guru Stron Jul 25 '21 at 08:57
  • @DanileTou Thx for the feedback, I didn't test it. So you need to specify the full destination file path not just the directory. I've edited my post – lidqy Jul 25 '21 at 09:27