[C#][System.IO] About copying folders and the difference between (Directory and DirectoryInfo, File and FileInfo)
The problem this time is that I want to copy a folder, but after searching around, I found that only File has Copy or FileInfo’s CopyTo, and there is no copy operation method for Directory.
The method of copying a folder in C# is to first create a destination folder (destinationFolder) and then copy the files in the (soursefolder) to the destination folder in sequence. C# does not provide an encapsulated method to copy the files in the folder. Copy the entire file and its subfolders.
The following is the CopyFold code:
1 using System.IO; 2 3 class Program 4 { 5 static span> void Main() 6 { 7 string span> sourceFolder = @""; 8 string span> destinationFolder = @""; 9 10 CopyFolder(sourceFolder, destinationFolder); 11 } 12 13 static void CopyFolder(string sourceFolder, string destinationFolder) 14 { 15 DirectoryInfo dir = new DirectoryInfo(sourceFolder); 16 17 Directory.CreateDirectory(destinationFolder); 18 19 FileInfo[] files = dir. GetFiles(); 20 21 foreach (FileInfo file in files) 22 { 23 string span> destinationFile = Path.Combine(destinationFolder, file.Name); 24 file.CopyTo(destinationFile, false); 25 } 26 27 DirectoryInfo[] subDirs = dir. GetDirectories(); 28 29 foreach (DirectoryInfo subdir in subDirs) 30 { 31 string span> destinationSubDir = Path.Combine(destinationFolder, subdir.Name); 32 CopyFolder(subdir .FullName, destinationSubDir); 33 } 34 } 35 }
But there is a problem with the above code. If there are multiple sourcefolders and multiple JPG or TXT files in a parent folder, after changing the sourcefolder path to the parent path, the extra JPGs and TXT files will also be added at the same time. is copied, so some changes need to be made to the above code to copy only the specified folder.
Expand:
There is no difference between Directory and DirectoryInfo, File and FileInfo in the title. The one with the word “Info” provides a more flexible instance method, please note that! ! Example method! ! ! , before searching for information, I directly called the DirectoryInfo class with the same method as the Directory class, which was wrong.
Directory and File are static methods, so you can directly File.Copy(), Directory.GetDirectories()
DirectoryInfo and FileInfo are non-static and must be instantiated before their methods can be called. For example, DirectoryInfo.GetDirectories() is wrong! Only new DirectoryInfo().GetDirectories() can be used.