8

I am trying to create a directory and subdirectories and copy files from on one location to another location. The following code works but it doesn't create a parent directory(10_new) if there are sub directories. I am trying to copy all the contents(including subdirectories) from "c:\\sourceLoc\\10" to "c:\\destLoc\\10_new" folder. If "10_new" doesn't exist then I should create this folder. Please assist.

string sourceLoc = "c:\\sourceLoc\\10";
string destLoc = "c:\\destLoc\\10_new";

foreach (string dirPath in Directory.GetDirectories(sourceLoc, "*", SearchOption.AllDirectories))
{
    Directory.CreateDirectory(dirPath.Replace(sourceLoc, destLoc));
    if (Directory.Exists(sourceLoc))
    {
         //Copy all the files
         foreach (string newPath in Directory.GetFiles(sourceLoc, "*.*", SearchOption.AllDirectories))
             File.Copy(newPath, newPath.Replace(sourceLoc, destLoc));
    }
}
Suraj Shrestha
  • 1,790
  • 1
  • 25
  • 51
nav100
  • 2,923
  • 19
  • 51
  • 89
  • Idk if there is an easy peasy library function already but you could recursively check for subfolders and copy each one across. – Amicable Feb 28 '13 at 16:12
  • Please check http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c-sharp – Stefano Altieri Feb 28 '13 at 16:13

4 Answers4

10

Here is how to copy all files in a directory to another directory

This is taken from http://msdn.microsoft.com/en-us/library/cc148994.aspx

string sourcePath = "c:\\sourceLoc\\10";
string targetPath = "c:\\destLoc\\10_new";
string fileName = string.Empty;
string destFile = string.Empty;

// To copy all the files in one directory to another directory. 
// Get the files in the source folder. (To recursively iterate through 
// all subfolders under the current directory, see 
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously 
//       in this code example. 
if (System.IO.Directory.Exists(sourcePath))
{
    string[] files = System.IO.Directory.GetFiles(sourcePath);

    // Copy the files and overwrite destination files if they already exist. 
    foreach (string s in files)
    {
        // Use static Path methods to extract only the file name from the path.
        fileName = System.IO.Path.GetFileName(s);
        destFile = System.IO.Path.Combine(targetPath, fileName);
        System.IO.File.Copy(s, destFile, true);
    }
}
else
{
    Console.WriteLine("Source path does not exist!");
}

Recursive Directory/Sub-directory

public class RecursiveFileSearch
{
    static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();

    static void Main()
    {
        // Start with drives if you have to search the entire computer.
        string[] drives = System.Environment.GetLogicalDrives();

        foreach (string dr in drives)
        {
            System.IO.DriveInfo di = new System.IO.DriveInfo(dr);

            // Here we skip the drive if it is not ready to be read. This
            // is not necessarily the appropriate action in all scenarios.
            if (!di.IsReady)
            {
                Console.WriteLine("The drive {0} could not be read", di.Name);
                continue;
            }
            System.IO.DirectoryInfo rootDir = di.RootDirectory;
            WalkDirectoryTree(rootDir);
        }

        // Write out all the files that could not be processed.
        Console.WriteLine("Files with restricted access:");
        foreach (string s in log)
        {
            Console.WriteLine(s);
        }
        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key");
        Console.ReadKey();
    }

    static void WalkDirectoryTree(System.IO.DirectoryInfo root)
    {
        System.IO.FileInfo[] files = null;
        System.IO.DirectoryInfo[] subDirs = null;

        // First, process all the files directly under this folder
        try
        {
            files = root.GetFiles("*.*");
        }
        // This is thrown if even one of the files requires permissions greater
        // than the application provides.
        catch (UnauthorizedAccessException e)
        {
            // This code just writes out the message and continues to recurse.
            // You may decide to do something different here. For example, you
            // can try to elevate your privileges and access the file again.
            log.Add(e.Message);
        }

        catch (System.IO.DirectoryNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }

        if (files != null)
        {
            foreach (System.IO.FileInfo fi in files)
            {
                // In this example, we only access the existing FileInfo object. If we
                // want to open, delete or modify the file, then
                // a try-catch block is required here to handle the case
                // where the file has been deleted since the call to TraverseTree().
                Console.WriteLine(fi.FullName);
            }

            // Now find all the subdirectories under this directory.
            subDirs = root.GetDirectories();

            foreach (System.IO.DirectoryInfo dirInfo in subDirs)
            {
                // Resursive call for each subdirectory.
                WalkDirectoryTree(dirInfo);
            }
        }            
    }
}
abc123
  • 17,855
  • 7
  • 52
  • 82
  • it is not copying sub folder images. – Billy Oct 22 '13 at 09:51
  • @Billy directly from the above: To recursively iterate through all subfolders under the current directory, see "How to: Iterate Through a Directory Tree. – abc123 Oct 22 '13 at 18:42
9

From looking at your code, you never check for the existence of the parent folders. You jump to getting all the child folders first.

if (!Directory.Exists(@"C:\my\dir")) Directory.CreateDirectory(@"C:\my\dir");
Justin
  • 3,337
  • 3
  • 16
  • 27
1

Before doing File.Copy, check to make sure the folder exists. If it doesn't create it. This function will check if a path exists, if it doesnt, it will create it. If it fails to create it, for what ever reason, it will return false. Otherwise, true.

 Private Function checkDir(ByVal path As String) As Boolean
        Dim dir As New DirectoryInfo(path)
        Dim exist As Boolean = True
        If Not dir.Exists Then
            Try
                dir.Create()
            Catch ex As Exception
                exist = False
            End Try
        End If
        Return exist
    End Function

Remember, all .Net languages compile down to the CLR (common language runtime) so it does not matter if this is in VB.Net or C#. A good way to convert between the two is: http://converter.telerik.com/

jason
  • 3,821
  • 10
  • 63
  • 120
  • The question is about C#, not VB – Forte L. Feb 28 '13 at 16:15
  • all .Net languages compile down to the CLR and can be easily converted between languages (http://converter.telerik.com/). Furthermore, this questions isn't language dependent, they are not asking about syntax. – jason Feb 28 '13 at 16:16
  • I agree with jason. Doesnt metter what language you use, you should understand what the logic is beside this code! – Maris Feb 28 '13 at 16:19
  • Thanks, I would appreciate an up vote if you agree and the removal of the downvote if you also agree Forte – jason Feb 28 '13 at 16:20
  • @jason, you can only undo a downvote if the answer is edited. – Forte L. Feb 28 '13 at 16:50
  • Although I agree with what you said, the person who asked the question might not understand VB syntax. If you want to show logic then use pseudo code instead of a specific language. (just my opinion) – Forte L. Feb 28 '13 at 16:52
  • Thank you for removing the down vote. I understand your point but my fear would be that users would refuse to answer questions they knew the answer to in fear of getting down voted because it is in a different syntax. – jason Feb 28 '13 at 17:50
-5

It is impossible to copy or move files with C# in windows 7.

It will instead create a file of zero bytes.

cande
  • 1