不能移动目录中的多个文件

本文关键字:文件 移动 不能 | 更新日期: 2023-09-27 17:49:37

我试图将目录中的多个文件移动到存档子文件夹。我使用foreach循环来实现这个想法。不幸的是,只有当目录中只有一个文件时,它才能移动文件。但当我把多个目录directory .move();不能工作。有人能帮我吗?

static string antJsonSerializer(){
    #region  KDI SALES
    string[] allfiles = Directory.GetFiles(@"C:'xml'"); // Put all file names in root directory into array.
    string sourceDirectory = @"C:'xml'";
    string destinationDirectory = @"C:'xml'Archive'";
    // Check if directories are existing -- Working
    bool xmlRoot = System.IO.Directory.Exists(sourceDirectory);
    if (!xmlRoot) System.IO.Directory.CreateDirectory(sourceDirectory);
    bool xmlArchive = System.IO.Directory.Exists(destinationDirectory);
    if (!xmlArchive) System.IO.Directory.CreateDirectory(destinationDirectory);
    AntHelpers drone = new AntHelpers();
    foreach (string name in allfiles)
    {
        try
        {
            drone.xmltosql(@name.Trim());
            //File.Move(@name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");  //Not working     
            Directory.Move(@name, destinationDirectory + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");       
            //Directory.Move(sourceDirectory, destinationDirectory); //Not working
        }
        catch (Exception e)
        {
            //Console.WriteLine("Main Process Catch ERR: " + e.Message);
            //ErrLogtoDB(string TRNTYPE, string extserial, string texttowrite, string logfilename)
            AntHelpers.ErrLogtoDB("SALES", @name, "Ant JSON Serializer Failed: " + e.Message, 
                "LeafCutterLogFile_JSONSerializer_" + (DateTime.Now.Year).ToString() + (DateTime.Now.Month).ToString().PadLeft(2, '0') + (DateTime.Now.Day).ToString().PadLeft(2, '0') + (DateTime.Now.Hour).ToString().PadLeft(2, '0') + ".html");               
        }                
        //drone.ExtractSQLSendAntHill(); //For testing: OFF 
    #endregion
    return " !!!! Work Complete !!!! ";
}

不能移动目录中的多个文件

您试图将年+月+日+小时.html文件保存为"NAME"。如果有多个文件,那么如何用相同的文件名保存它?相反,您应该添加秒和/或毫秒,或者使用其他东西来区分文件并使其具有唯一名称。否则,取不带扩展名的文件名,然后添加年、月、日和小时。这就是为什么您不能一次移动多个文件,因为当尝试移动第二个文件时,将抛出异常,说"无法移动现有文件"。

目录。Move接受源目录和目标目录,而不是文件路径。试试这个:

Directory.Move(sourceDirectory, destinationDirectory);

也可以在foreach循环的最后运行