The best way to move a directory with all its contents(files or folders) in C#?

后端 未结 6 1843
萌比男神i
萌比男神i 2021-01-16 16:55

What is the best way to move directory with all its contents(files or folders) in C#?

I used the following codes, but it throws The Directory is not empty

6条回答
  •  臣服心动
    2021-01-16 17:44

    Use this would help you:

            string sourceDir = @"c:\test";
            string destinationDir = @"c:\test1";
    
            try
            {
                // Ensure the source directory exists
                if (Directory.Exists(sourceDir) == true )
                {
                    // Ensure the destination directory doesn't already exist
                    if (Directory.Exists(destinationDir) == false)
                    {
                        // Perform the move
                        Directory.Move(sourceDir, destinationDir);
                    }
                    else
                    {
                        // Could provide the user the option to delete the existing directory
                        // before moving the source directory
                    }
                }
                else
                {
                    // Do something about the source directory not existing
                }
            }
            catch (Exception)
            {
                // TODO: Handle the exception that has been thrown
            }
    

提交回复
热议问题