SoFunction
Updated on 2025-03-06

C# Copy the file to the specified folder and organize it

Below is a simple example of copying the file (clipping is copying first and then deleting) to the specified path and archived by date in C#. Two points worth noting are:

1) The path of the file is the key, and double slashes are used in the program\\

2) The difference between files and folders

private void DoWork()
{
   String dir="D:\\ABC"
   //Create backup folder and name it by time   String bakDir = dir + "\\bak\\" + ("yyyy-MM-dd");
 
   if ((bakDir) == false){
       (bakDir);
   }
   string[] files = (dir);
   if ( != 0) {
      foreach (string file in files) {
      FileInfo fileinfo = new FileInfo(file);
      try{
        string fileName = (dir, "");
        //Back up files        (file,(bakDir,fileName));
        (file);
      }  
   }
}

Attached the implementation method of other netizens:

private void CopyDir(string srcPath, string aimPath)
 {
 
 try
 
 {
 
 // Check whether the target directory ends with directory segmentation characters. If not, add 
 if (aimPath[ - 1] != )
 
 {
 
 aimPath += ;
 
 }
 
 // Determine whether the target directory exists or not, create a new one. 
 if (!(aimPath))
 {
 
 (aimPath);
 
 }
 
 // Get the file list of the source directory, which is an array containing the file and directory paths 
 // If you point to the file below the copy target file without including the directory, please use the following method 
 // string[] fileList = (srcPath);
 
 string[] fileList = (srcPath);
 
 // traverse all files and directories 
 foreach (string file in fileList)
 
 {
 
 // First treat it as a directory. If this directory exists, recursively copy the files below the directory. 
 if((file))
 
 {
 
 CopyDir(file, aimPath + (file));
 
 }
 
 // Otherwise, directly copy the file 
 else
 
 {
 
 (file, aimPath + (file),true);
 
 }
 
 }
 
 }
 
 catch(Exception e)
 {
 
 throw;
 
 }
 
 }
  }

It can be implemented without recursion, and the breadth-first algorithm can save stack space

using System;
using ;
using ;
using ;
string sourcepath=@"C:\sourcedir";
Queue<FileSystemInfo> copyfolders = new Queue<FileSystemInfo>(new DirectoryInfo(sourcepath).GetFileSystemInfos());
string copytopath = @"C:\targetdir";
copytopath = (() ==  - 1) ? copytopath : (copytopath+) + (sourcepath);
(copytopath);
while (>0)
{
  FileSystemInfo atom = ();
  FileInfo file = atom as FileInfo;
  if (file == null)
  {
    DirectoryInfo directory = atom as DirectoryInfo;
    ((sourcepath,copytopath));
    foreach (FileSystemInfo fi in ())
      (fi);
  }
  else
    ((sourcepath,copytopath));
}

The above is the entire content of this article, I hope you like it.