No Opinions...just code

Recursively Copy A Directory

1 private void CopyDirectory(String theSourcePath, String theDestPath, bool copySubDirs)

2 {

3 DirectoryInfo dir = new DirectoryInfo(theSourcePath);

4 DirectoryInfo[] dirs = dir.GetDirectories();

5

6 // If the source directory does not exist, throw an exception.

7 if (!dir.Exists)

8 {

9 throw new DirectoryNotFoundException(

10 "Source directory does not exist or could not be found: " + theSourcePath);

11

12 }

13

14 // If the destination directory does not exist, create it.

15 if (!Directory.Exists(theDestPath))

16 {

17 Directory.CreateDirectory(theDestPath);

18 }

19

20

21 // Get the file contents of the directory to copy.

22 FileInfo[] files = dir.GetFiles();

23

24 foreach (FileInfo file in files)

25 {

26 // Create the path to the new copy of the file.

27 string temppath = Path.Combine(theDestPath, file.Name);

28

29 // Copy the file.

30 file.CopyTo(temppath, false);

31 }

32

33 // If copySubDirs is true, copy the subdirectories.

34 if (copySubDirs)

35 {

36

37 foreach (DirectoryInfo subdir in dirs)

38 {

39 // Create the subdirectory.

40 string temppath = Path.Combine(theDestPath, subdir.Name);

41

42 // Copy the subdirectories.

43 CopyDirectory(subdir.FullName, temppath, copySubDirs);

44 }

45 }

46 }

47

48 private void CopyFile(String theSourcePath, String theDestPath, bool doOverWrite)

49 {

50 FileInfo fi = new FileInfo(theSourcePath);

51

52 if (!fi.Exists)

53 {

54 throw new FileNotFoundException();

55 }

56 File.Copy(theSourcePath, theDestPath, doOverWrite);

57 }

0 comments: