public static void CopyPackFiles() { var SB = new StringBuilder(); bool Exists = Directory.Exists(@"C:\GamePack"); try { if (!Exists) { Directory.CreateDirectory(str2 + folder); foreach (var file in new DirectoryInfo(GetPath()).GetFiles("*.d3d", SearchOption.TopDirectoryOnly)) { file.CopyTo(Path.Combine(str2, file.Name)); } foreach (var file2 in new DirectoryInfo(GetPath() + folder).GetFiles("*.ini", SearchOption.TopDirectoryOnly)) { file2.CopyTo(Path.Combine(str2 + folder, file2.Name)); } } } catch (IOException e) { SB.AppendLine(e.ToString()); } catch (SecurityException e) { SB.AppendLine(e.ToString()); } catch (Exception e) { SB.AppendLine(e.ToString()); } File.WriteAllText("Error.log", SB.ToString()); } 

How to copy files to 1 part of a folder, and 2 part to an internal folder using Linq?

Is it possible to do without a secondary cycle (where the files are copied into the internal folder) ?!

Should I use Task in this example?

  • one
    Ways worth adding through Path.Combine . Instead of new DirectoryInfo(GetPath() + folder).GetFiles you can use Directory.GetFiles . LINQ is not particularly needed here, maximum - you can glue the result of two calls to GetFiles through Concat , and drive one cycle according to the result :) - PashaPash
  • @PashaPash, Can you give an example as an answer) - GooliveR
  • @PashaPash, By the way, I kind of seemed to use Path.Combine inside the loop) I’m wondering how to fold Concat with Concat in 1 loop, kindly give me some example code, I just didn’t see how they do it when copying or the like. - GooliveR
  • You used Path.Combine, but not in all places. str2 + folder . I would post an example, but with LINQ it turns out to be scary and less readable. LINQ is used to build queries. And you do not need a request here, two cycles (or a method) are simpler and more readable. Neither LINQ nor Task is needed here. - PashaPash
  • Clearly, that is, just for the place + we put Path.Combine :) Thank you, but it's still interesting to see Concat in one cycle - GooliveR

1 answer 1

 string targetBaseFolder = str2; string targetSubFolder = Path.Combine(targetBaseFolder, folder); // один раз, а не в цикле Directory.CreateDirectory(targetSubFolder); string sourceFolder = GetPath(); string sourceSubfolder = Path.Combine(sourceFolder, folder); CopyFiles(sourceFolder, targetBaseFolder, "*.d3d"); CopyFiles(sourceSubfolder, targetSubFolder, "*.ini"); private static void CopyFiles(string from, string to, string searchPattern) { // SearchOption.TopDirectoryOnly - значение по умолчанию foreach (var file in Directory.GetFiles(from, searchPattern)) { File.Copy(file, Path.Combine(to, Path.GetFileName(file))); } } 

LINQ is not needed. Task - depending on who is calling this code and whether it is waiting for asynchrony