【问题标题】:copy files from one location to another将文件从一个位置复制到另一个位置
【发布时间】:2013-02-28 16:09:36
【问题描述】:

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

【问题讨论】:

标签: c# asp.net


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 它没有复制子文件夹图像。
    • @Billy 直接从上面:要递归遍历当前目录下的所有子文件夹,请参阅“如何:遍历目录树。
    【解决方案3】:

    在执行 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/

    【讨论】:

    • 问题是关于 C#,而不是 VB
    • 所有 .Net 语言都编译为 CLR,并且可以在语言之间轻松转换 (converter.telerik.com)。此外,这个问题不依赖于语言,它们不询问语法。
    • 我同意杰森的观点。不管你用什么语言,你应该明白这段代码旁边的逻辑是什么!
    • 谢谢,如果您同意,我将不胜感激,如果您也同意 Forte,请删除反对票
    • @jason,如果答案已被编辑,您只能撤消反对票。
    【解决方案4】:

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

    它将改为创建一个零字节的文件。

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多