'How to minimize c# instead of using numbers of for each

I have a list of directories where I am supposed to copy their contents to pre-defined output locations. How do I create a function to perform this operation?

using System;
using System.IO;

namespace doos_date_change
{
    class Program
    {
        static void Main(string[] args)
        {
            var doosdate = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");

            string Fax_Single_General_Nontask_01inputlocation = @"location_path" + doosdate + "_01" + "\\" + "General_Nontask" + "\\";
            string Fax_Single_General_Nontask_01Outputlocation = @"location_path" + doosdate + "_01" + "\\" + "General_Nontask" + "\\";

            if (Directory.Exists(Fax_Single_General_Nontask_01Outputlocation) == false)
            {
                Directory.CreateDirectory(Fax_Single_General_Nontask_01Outputlocation);
            }

            foreach (var srcPath in Directory.GetFiles(Fax_Single_General_Nontask_01inputlocation))
            {
                File.Copy(srcPath, srcPath.Replace(Fax_Single_General_Nontask_01inputlocation, Fax_Single_General_Nontask_01Outputlocation), true);
            }

            //the steps above are repeated for many directories.
        }
    }
}


Solution 1:[1]

Looking at the code, you're performing the same operations repeatedly:

  1. calculate the input path
  2. calculate the output path
  3. create a directory if it doesn't exist
  4. copy the contents from the input to the output.

You can write a single function that does this for you:

static readonly string rootPath = $"location_path{DateTime.Now.AddDays(-1):yyyyMMdd}";

static void CopyFiles(int number, string folder)
{
    var inputPath  = $"{rootPath}_{number:00}\\{folder}\\";
    
    //your code sample generates the same input location and output location
    //so you'll need to fix it appropriately.
    var outputPath = $"{rootPath}_{number:00}\\{folder}\\";

    //no need to check if the directory exists, CreateDirectory handles that
    Directory.CreateDirectory(outputPath);

    foreach (var file in Directory.GetFiles(inputPath))
    {
        //make a copy of the file, using the same name, but in the
        //output location directory
        File.Copy(file, Path.Combine(outputPath, Path.GetFileName(file)), true);
    }
}

With this function, then in your main program, you can do something like this:

static void Main(string [] args)
{
    var locations = new string[] 
    {  
       "General_NonTask",
       "General_Task",
       //...add all of your locations
    };

    for (int i = 1; i <= 2; i++)
    {
        foreach (var location in locations)
        {
           CopyFiles(i, location);
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John V