2013-05-31 36 views
-1

我在C:\Source文件夹中有一堆文本文件。 我想要将所有文件复制到MyData文件夹的整个C:\ drive。 请让我知道在C#中的方法,我想这将是一个递归的。将文件复制到C#中的驱动器中的特定文件夹

我知道如何将文件从一个位置复制到另一个位置。 我想要的方法来获取所有的文件夹/目录名称“MyData”跨C :. 而文件夹“MyData”位于多个位置。所以我想将这些文件复制到所有的地方。

+4

请出示目前的努力和代码 –

+1

@Frederick罗斯 - 在OP听起来并不像他知道从哪里开始,没有IMO所需的代码问那种问题。 – killthrush

+0

@Dev Dhingra - 如果你想知道你的问题为什么被低估,那可能是因为它“没有显示研究工作”。其他人之前已经问过(并回答过)这个问题,并且很容易找到我使用谷歌提供的链接。下一次要考虑的事情。 – killthrush

回答

0

如果你真的不知道从哪里开始,我建议你看看this question,这个问题在一段时间后被问到。有很多例子和链接可以帮助你入门。

2

这个答案是直接取自MSDN这里:http://msdn.microsoft.com/en-us/library/bb762914.aspx

using System; 
using System.IO; 

class DirectoryCopyExample 
{ 
    static void Main() 
    { 
     // Copy from the current directory, include subdirectories. 
     DirectoryCopy(".", @".\temp", true); 
    } 

private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) 
{ 
    // Get the subdirectories for the specified directory. 
    DirectoryInfo dir = new DirectoryInfo(sourceDirName); 
    DirectoryInfo[] dirs = dir.GetDirectories(); 

    if (!dir.Exists) 
    { 
     throw new DirectoryNotFoundException(
      "Source directory does not exist or could not be found: " 
      + sourceDirName); 
    } 

    // If the destination directory doesn't exist, create it. 
    if (!Directory.Exists(destDirName)) 
    { 
     Directory.CreateDirectory(destDirName); 
    } 

    // Get the files in the directory and copy them to the new location. 
    FileInfo[] files = dir.GetFiles(); 
    foreach (FileInfo file in files) 
    { 
     string temppath = Path.Combine(destDirName, file.Name); 
     file.CopyTo(temppath, false); 
    } 

    // If copying subdirectories, copy them and their contents to new location. 
    if (copySubDirs) 
    { 
     foreach (DirectoryInfo subdir in dirs) 
     { 
      string temppath = Path.Combine(destDirName, subdir.Name); 
      DirectoryCopy(subdir.FullName, temppath, copySubDirs); 
     } 
    } 
} 

}

1

你可以在System.IO命名空间使用FileSystemWatcher类的。

public void FolderWatcher() 
    { 
     FileSystemWatcher Watcher = new System.IO.FileSystemWatcher(); 
     Watcher.Path = @"C:\Source"; 
     Watcher.Filter="*.txt"; 
     Watcher.NotifyFilter = NotifyFilters.LastAccess | 
        NotifyFilters.LastWrite | 
        NotifyFilters.FileName | 
        NotifyFilters.DirectoryName; 
     Watcher.Created += new FileSystemEventHandler(Watcher_Created); 
     Watcher.EnableRaisingEvents = true; 

    } 

    void Watcher_Created(object sender, FileSystemEventArgs e) 
    {    
     File.Copy(e.FullPath,"C:\\MyData",true);    
    } 
相关问题