如何将子目录移动到其他现有的根目录中

问题描述 投票:0回答:1

我正在编写一个导入数据库的控制台应用程序,在导入之后,我想将刚导入的文件移动到名为DELETE的目录中。我这样做是因为我想在实际删除它们之前将它们保留大约一个月。问题是我不断收到错误消息

Cannot create 'DELETE' because a file or directory with the same name already exists

我知道这应该很简单,但是出于某种原因,我一直遇到问题。这是我编写的用于移动文件的方法。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace DicomImporter.FileMethods
{
    class MoveFiles
    {
        /// <summary>
        /// After import the files move them all to a delete directory.
        /// </summary>
        public static void MoveFilesAfterImport(string dicom_dir, string delete_dir)
        {
            try
            {

                //getting all the subdirectories into an array
                string[] subdir = Directory.GetDirectories(dicom_dir);
                foreach (string path in subdir)
                {
                    //need to get my paths into DirectoryInfo data types so that I can use the Moveto() method
                    DirectoryInfo dicom_direct = new DirectoryInfo(path);
                    if (Directory.Exists(delete_dir))
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("Moving " + path + " to the DELETE directory");
                        Console.ForegroundColor = ConsoleColor.White;
                        dicom_direct.MoveTo(delete_dir);
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Something went wrong while trying to move the subject folder");
                        Console.ForegroundColor = ConsoleColor.White;
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

我提供的两个参数是包含我要移动的所有子目录的目录,以及包含目的地目录的DELETE目录。

c#
1个回答
0
投票

[我认为您正在尝试将dicom_dir移到delete_dir,可能出现的问题是,在下一次导入时,dicom_dir已经存在delete_dir,因此您将无法移动...] >

一种解决方案是为每个导入都赋予一个唯一的名称,因此您可以将目录移动到目标文件夹...另一种方法是将目录的内容移动到目标文件夹,如下所示:

DirectoryInfo dicom_info = new DirectoryInfo(dicom_dir);

FileInfo[] files = dicom_info.GetFiles();

foreach (FileInfo file in files)
{
    if (file.Length > 0)
    {
         string destFullPath = Path.Combine(delete_dir + file.Name)

        // delete the file if it already exists in the destination
        if (File.Exists(destFullPath);
        {
            File.Delete(destFullPath);
        }

        // copy the file to destination
        file.MoveTo(destFullPath);
    }
}

-1
投票

Microsoft文档提供了此example

© www.soinside.com 2019 - 2024. All rights reserved.