c# - Check if a file name exists more than once in a FileInfo array -


fileinfo[] folderfiles = folder.getfiles();  foreach (fileinfo file in folderfiles) {      int filecount = 0;      streamwriter sw = null;      string filename = path.getfilenamewithoutextension(file.name);      string[] brkedfilename = filename.split('_');      string stringtocheck = brkedfilename[3];      (int = 0; <= folderfiles.count() - 1; i++)     {         string filename2 = folderfiles[i].name;          string[] brkedfilename2 = filename2.split('_');          if (brkedfilename2[3] == stringtocheck)         {             filecount = ++filecount;              if (filecount == 2)            {                 sw = new streamwriter(folderpath + "/" + newfilename, true);                 sw.writeline(stringtocheck + "  " + "--" + "  " + "repeated in folder " + " " + folder.name);                 sw.close();             }         }     } } 

by doing way, if file name existing 2 times , writing file name 2 times. want write once.

any appreciated. in advance. :)

you can use linq find files same brkednames:

var repeatedfiles = f in folderfiles                     let brkedname = path.getfilenamewithoutextension(f.name).split('_')[3]                     group f brkedname g                     g.count() > 1                     select new                     {                         brkedname = g.key,                         count = g.count(),                         files = g                     }; 

this query groups files 4th part of splitted names (note: in original code don't check if there @ least 4 parts) , select groups more 1 file. provides stats - brked name, count of files same name , files collection.

foreach(var group in repeatedfiles)    sw.writeline($"{group.brkedname} -- repeated {group.count} times in {folder.name}"); 

Comments