简体   繁体   English

如何在没有异常的情况下将文件从目录移动到另一个目录

[英]How can I move my files from my directory to another directory without getting an exception

It keeps throwing an exception: 它总是抛出异常:

Ant JSON Serializer Failed: The process cannot access the file because it is being used by another process. Ant JSON序列化程序失败:该进程无法访问该文件,因为该文件正在被另一个进程使用。

I know there are a lot of posts out there to fix that exception but it won't apply to my code. 我知道有很多帖子可以解决该异常,但是它不适用于我的代码。 Can anyone point me to the right direction? 谁能指出我正确的方向?

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 !!!! ";
}

Try this one: 试试这个:

// Ensure that the target does not exist. 
if (File.Exists(destinationPath))   
    File.Delete(destinationPath);

// Move the file.
File.Move(sourcePath, destinationPath);

Refer File.Move Method for more details. 有关更多详细信息,请参考File.Move方法

Your current code is trying to move the entire directory - try File.Move instead: 您当前的代码正在尝试移动整个目录-尝试使用File.Move

string newPath = Path.Combine(destinationDirectory, Path.GetFileName(name));
File.Move(name, newPath);

Thank you to both of you @C.Evenhuis & @manoj_rp. 谢谢@ C.Evenhuis和@manoj_rp。 I fixed my File.Move(); 我修复了File.Move(); It is now File.Move(@name, "ArchivedlogName.txt"); 现在是File.Move(@name,“ ArchivedlogName.txt”); I'll up-vote both. 我都投票。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM