-1

我在文件夹中有一堆文本文件C:\Source。我想将所有文件复制MyDataC:\ drive. 请让我知道 C# 中的方法,我认为这将是一种递归方法。

我知道如何将文件从一个位置复制到另一个位置。我想获得在 C: 中获取所有名称为“MyData”的文件夹/目录的方法。并且文件夹“ MyData ”位于多个位置。所以我想将文件复制到所有地方。

4

3 回答 3

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

}

于 2013-05-31T13:54:07.290 回答
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);            
    }
于 2013-05-31T14:04:47.253 回答
0

如果您真的不知道从哪里开始,我建议您看一下不久前提出的这个问题。有很多示例和链接可以帮助您入门。

于 2013-05-31T13:38:31.007 回答