7

我正在尝试创建一个目录和子目录,并将文件从一个位置复制到另一个位置。以下代码有效,但如果有子目录,它不会创建父目录(10_new)。我正在尝试将所有内容(包括子目录)从"c:\\sourceLoc\\10"文件"c:\\destLoc\\10_new"夹复制。如果"10_new"不存在,那么我应该创建这个文件夹。请协助。

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));
    }
}
4

4 回答 4

8

以下是如何将目录中的所有文件复制到另一个目录

这取自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!");
}

递归目录/子目录

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);
            }
        }            
    }
}
于 2013-02-28T16:19:20.250 回答
8

通过查看您的代码,您永远不会检查父文件夹是否存在。您首先跳到获取所有子文件夹。

if (!Directory.Exists(@"C:\my\dir")) Directory.CreateDirectory(@"C:\my\dir");
于 2013-02-28T16:19:50.047 回答
2

在执行 File.Copy 之前,请检查以确保该文件夹存在。如果它不创建它。此函数将检查路径是否存在,如果不存在,它将创建它。如果它无法创建它,无论出于何种原因,它将返回 false。否则为真。

 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

请记住,所有 .Net 语言都编译为 CLR(公共语言运行时),因此无论是在 VB.Net 还是 C# 中都没有关系。在两者之间进行转换的一个好方法是: http ://converter.telerik.com/

于 2013-02-28T16:14:43.497 回答
-4

在 Windows 7 中无法使用 C# 复制或移动文件。

相反,它将创建一个零字节的文件。

于 2013-09-14T00:25:27.490 回答