c#在不同目录之间移动文件

时间:2016-06-01 15:16:07

标签: c#

这是我的整个代码,它读取csv文件并输出某些数字,然后将文件移动到另一个文件夹。我需要帮助修复的东西是它拉入文件的方式以及它移动它们的方式。我目前有两个名为Hotels和Completed Hotels的文件夹。在酒店文件夹中,它有6个不同酒店的子文件夹。它现在的工作方式,它将从整个酒店文件夹中立即从每个酒店文件夹中提取所有文件,并将它们全部移动到已完成的酒店文件夹中。我想要改变的是在每个酒店文件夹中都有一个已完成的文件夹,我希望它从酒店提取数据并将其放入自己已完成的文件夹中,然后移动到下一个酒店并执行相同的操作,我将如何更改我的代码来实现它?

以下代码:

class ManagerReport
{
    static void ProcessFilesCSVFiles(string originalPath, string destinationPath)
    {
        // first check if path exists
        if (!Directory.Exists(originalPath))
            // doesn't exist then exit, can't copy from something that doesn't exist
            return;
        var copyPathDirectory = new DirectoryInfo(originalPath);
        // using the SearchOption.AllDirectories will search sub directories
        var copyPathCSVFiles = copyPathDirectory.GetFiles("*.txt", SearchOption.AllDirectories);

        // loops through directory looking for txt files
        for (var i = 0; i < copyPathCSVFiles.Length; i++)
        {
            // get the file
            var csvFile = copyPathCSVFiles[i];

            // [...] parse and import the file

            // creates a variable that combines the the directory of the new folder with the file name
            var destinationFilePath = Path.Combine(destinationPath, csvFile.Name);
            // This loop prevents duplicates. If a file is already in the folder, it will delete the file already in there and move this one in.
            // Shouldn't be an issue since each file will have a different name
            if (File.Exists(destinationFilePath))
            {
                File.Delete(destinationFilePath);
            }
            // moves it to the new folder
            csvFile.MoveTo(destinationFilePath);
        }
    }

    static void Main(string[] args)
    {
        ProcessFilesCSVFiles(@"C:\Users\Documents\Hotels", @"C:\Users\Documents\Completed Hotels");
    }
}

1 个答案:

答案 0 :(得分:1)

基本上,你有一个像这样的源文件结构:

Prefix\Hotel1\File1.csv
Prefix\Hotel1\File2.csv
Prefix\Hotel2\File1.csv
Prefix\Hotel3\File3.csv

您要处理的内容然后移动到目标目录,如下所示:

Prefix\Hotel1\Completed\File1.csv
Prefix\Hotel1\Completed\File2.csv
Prefix\Hotel2\Completed\File1.csv
Prefix\Hotel3\Completed\File3.csv

您当前的代码使用DirectoryInfo.GetFiles(),它以递归方式扫描目录并返回完整路径。要确定哪个文件属于哪个文件夹,您需要再次拆分路径并确定父文件夹。

一个简单的解决方法是简单地遍历源目录,处理和移动文件:

foreach (var hotelDirectory in Directory.GetDirectories(sourceDirectory))
{
    foreach (var inputFile in Directory.GetFiles(hotelDirectory))
    {
        // process inputFile

        var destinationPath = Path.Combine(hotelDirectory, "Completed");
        Directory.CreateDirectory(destinationPath);

        var destinationFileName = Path.GetFileName(inputFile);
        destinationPath = Path.Combine(destinationPath, destinationFileName);

        File.Move(inputFile, destinationPath);
    }
}