我正在尝试将目录中的多个文件移动到存档子文件夹。我使用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 !!!! ";
}
答案 0 :(得分:1)
Directory.Move采用源和目标目录,而不是文件路径。试试这个:
Directory.Move(sourceDirectory, destinationDirectory);
此外,它可以在最后一次运行 - 在foreach循环之后。
答案 1 :(得分:1)
您正在尝试将年份+月份+日期+ hour.html的文件另存为“NAME”。如果有多个文件,那么如何使用相同的文件名保存?相反,您应该添加秒和/或毫秒,或使用其他东西来区分文件并使其成为唯一的名称。否则,在没有扩展名的情况下获取文件名,然后添加年,月,日和小时。这就是为什么你不能一次移动多个文件的原因,因为当试图移动第二个文件时会抛出异常,说“无法移动现有文件。”