将文件从一个位置复制到另一个位置

8

我正在尝试创建一个目录和子目录,并将文件从一个位置复制到另一个位置。以下代码可以工作,但如果有子目录,则不会创建父目录(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));
    }
}

我不知道是否有一个易于使用的库函数,但您可以递归地检查子文件夹并将每个文件夹复制到另一个位置。 - Amicable
请查看以下网址:https://dev59.com/kHVD5IYBdhLWcg3wL4iM - Stefano Altieri
4个回答

10

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

这来自于 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);
            }
        }            
    }
}

它不会复制子文件夹中的图片。 - Billy
@Billy 直接从上面开始:要递归地迭代当前目录下的所有子文件夹,请参阅“如何:迭代通过目录树”。 - abc123

9

从你的代码来看,你从未检查父文件夹是否存在。你首先跳转到获取所有子文件夹。

if (!Directory.Exists(@"C:\my\dir")) Directory.CreateDirectory(@"C:\my\dir");

1

在执行File.Copy之前,检查文件夹是否存在。如果不存在,则创建它。 此函数将检查路径是否存在,如果不存在,则创建它。如果由于任何原因无法创建它,则返回false。否则返回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

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


问题是关于C#,不是VB。 - Forte L.
所有的 .Net 语言都可以编译为 CLR 并且可以在语言之间轻松转换(http://converter.telerik.com/)。此外,这个问题并不依赖于语言,他们并不是在问语法。 - jason
我同意Jason的观点。无论使用什么编程语言,你都应该理解代码背后的逻辑! - Maris
谢谢,如果您同意,请点赞,并移除反对票,谢谢。Forte - jason
@jason,如果答案被编辑过,你才能撤回一个踩的评价。 - Forte L.
显示剩余2条评论

-5

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

相反,它会创建一个大小为零字节的文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接