Actually a subject)

Naryscal example:

void CopyDir(string FromDir, string ToDir) { Directory.CreateDirectory(ToDir); foreach (string s1 in Directory.GetFiles(FromDir)) { string s2 = ToDir + "\\" + Path.GetFileName(s1); File.Copy(s1,s2); } foreach (string s in Directory.GetDirectories(FromDir)) { CopyDir(s, ToDir + "\\" + Path.GetFileName(s)); } } 

Are there any more serious methods?

  • in the sense of "more serious"? copying the folder tree is a classic recursive algorithm, which is more serious? except that your algorithm lacks protection against exceptions when working with filesystem objects, and they will be guaranteed if you run the program outside of the prepared test environment - rdorn
  • You can replace the Directory and File classes with DirectiryInfo and FileInfo, it will be possible to write everything in one cycle, but with an internal condition for type checking, or in general LINQ request should be wrapped in one line, You don’t need to do this, working with file systems requires accuracy and attention to exceptions. What to do if during copying the folder you changed the rights to the folder? And there are a lot of such questions - rdorn
  • Well, here you have free arguments about file transactions ru.stackoverflow.com/a/502739/198316 , everything seems to be taken into account, including an electrician with a switch, but limited use. - rdorn

2 answers 2

The times of single-tasking single-user OS are gone, at least on the PC. There you could not afford to check the rights to files and not be afraid. that after checking for the presence of a file (all of a sudden!) will not appear when reading. But there were problems that needed to be solved, for example, read errors at the hardware level.

The file system is unstable. Anything can happen, from a power outage, to a change in the rights of a harmful admin right while your program is running. And this must be taken into account.

Copying the folder tree as a basic algorithm is not difficult, the classic recursive detour in depth or width, at the discretion of the author. There are several of them in the question and the adjacent answer. But in a multi-user multitasking environment, it is necessary to take into account the peculiarities of this environment at each stage of the algorithm.

1. Mandatory exception handling.

File operations can generate (and generate) a mass of various exceptions ( exceptions File.Open ). For good, each type of exception must be handled in a separate catch , why see below.

2. Copying folder operation complex and long

For us, this means that before implementing the algorithm, you need to answer a few questions and, based on the answers to these questions, implement exception handling. Sample list of questions:

  • an exception occurred at the nth step of the operation: ignore, abort the operation, ask the user?
  • as mentioned above, exceptions are different, respectively, how will we respond to specific types of exceptions?
  • What to do with the already processed objects of the interrupted operation: delete, leave as is?
  • if you delete, then how to deal with the replaced files? Yes, yes, there must be backup or shadow copy, or CVS, or whatever else you can think of. and if they are not?

And I have not yet mentioned the possible disconnection of the carrier by a careless user during copying, broken clusters, an electrician with a switch, a welder's neighbor, the weather on Venus, and many more, which one way or another could trigger an exception.

3. No silver bullet

All the listed and not listed questions will have to be answered for any operations with files, in some cases the answers are simple, some are not. There is no universal solution. Somewhere need reliability, somewhere data integrity, somewhere speed, and somewhere no annoying user questions. The goals are different, the solutions too.

The general recommendation may be as follows:

  • Do not be afraid of exceptions when working with the file system, they are and need to be properly used. For speed and performance-hungry maniacs, operations with file system objects on any of the modern media, including RAM disks, are slower than the generation and handling of exceptions. Do not save on matches.
  • forget about File.Exists , it is not an assistant in a modern environment, unless of course your goal is anything other than checking for the existence of a file / folder itself.
  • wrap in try catch finaly all operations with filesystem objects.
  • Ensure the correct completion of the operation, interrupted by an exception, if possible.
  • if the program's logic allows, notify the user about the problems immediately, not necessarily intrusive, you can simply output to the console or log, if a solution is not required from the user, or more persistently, if you cannot do without his active intervention.
  • If the operation can damage the data (overwrite, delete, etc.), re-ask the user for his confidence. Yes, users will use foul language (I, too, yes, yes =)), but you and the user will have at least a little confidence that he, and not his cat or 3-year-old child, performed this action.

    Option 1:

     //Создать идентичную структуру папок foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories)) { try { Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath)); } catch(Exception e) { //здесь обрабатывай ошибки } } //Копировать все файлы и перезаписать файлы с идентичным именем foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories)) { try { File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true); } catch(Exception e) { //здесь обрабатывай ошибки } } 

    Option 2

     Process proc = new Process(); proc.StartInfo.UseShellExecute = true; proc.StartInfo.FileName = @"C:\WINDOWS\system32\xcopy.exe"; proc.StartInfo.Arguments = $"{SourcePath} {DestinationPath} /E /I"; // /E = скопировать подпапки(пустые в том числе!). // /I = если дестинейшн не существует, создать папку с нужным именем. proc.Start(); 

    Option 3:

    Add a reference to the Visual Basic library and use the method:

     Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory); 

    All answers are taken with Google from: https://stackoverflow.com/questions/58744/copy-the-entire-contents-of-a-directory-in-c-sharp and slightly modified / added comments

    • @rdom, Is there an alternative? checked crumbling). - GooliveR
    • 2
      @ArteS alternative is written in my first comment on the question, add try blocks .. catch inside cycles and think about how to react to certain exceptions - rdorn
    • But the minus is not deserved. The given examples as an example of possible solutions are quite valid - rdorn