简体   繁体   中英

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.

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.

Your current code is trying to move the entire directory - try File.Move instead:

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

Thank you to both of you @C.Evenhuis & @manoj_rp. I fixed my File.Move(); It is now File.Move(@name, "ArchivedlogName.txt"); I'll up-vote both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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