[英]How can I fix my code to move files that already exist to another directory?
[英]How can I move my files from my directory to another directory without getting an exception
它总是抛出异常:
Ant JSON序列化程序失败:该进程无法访问该文件,因为该文件正在被另一个进程使用。
我知道有很多帖子可以解决该异常,但是它不适用于我的代码。 谁能指出我正确的方向?
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
bool xmlRoot = System.IO.Directory.Exists(sourceDirectory);
if (!xmlRoot) System.IO.Directory.CreateDirectory(sourceDirectory);
bool xmlArchive = System.IO.Directory.Exists(sourceDirectory);
if (!xmlArchive) System.IO.Directory.CreateDirectory(sourceDirectory);
AntHelpers drone = new AntHelpers();
foreach (string name in allfiles)
{
try
{
drone.xmltosql(@name.Trim());
Directory.Move(sourceDirectory, destinationDirectory); //Archive
}
catch (Exception e)
{
//Console.WriteLine("Main Process Catch ERR: " + e.Message);
//ErrLogtoDB(string TRNTYPE, string extserial, string texttowrite, string logfilename)
AntHelpers.ErrLogtoDB("SALES", "", "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 !!!! ";
}
试试这个:
// Ensure that the target does not exist.
if (File.Exists(destinationPath))
File.Delete(destinationPath);
// Move the file.
File.Move(sourcePath, destinationPath);
有关更多详细信息,请参考File.Move方法 。
您当前的代码正在尝试移动整个目录-尝试使用File.Move
:
string newPath = Path.Combine(destinationDirectory, Path.GetFileName(name));
File.Move(name, newPath);
谢谢@ C.Evenhuis和@manoj_rp。 我修复了File.Move(); 现在是File.Move(@name,“ ArchivedlogName.txt”); 我都投票。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.