File.Exists + File.Move Erroring "The process cannot access the file because it is being used by another process."

Marshal Alessi picture Marshal Alessi · Jul 9, 2017 · Viewed 10.7k times · Source

I have what I thought would be a very simple file mover script. It checks for a file and moves it to a new directory if it exists:

if (File.Exists(_collection[x,0]))
{
    System.IO.File.Move(_collection[x, 0], _moveTo);
    MessageBox.Show("File moved because it was stale.");
}

It passes the check that the file exists, but then errors on the following line when trying to move it stating that the file is being used by another process. I can only assume that File.Exists is causing it to hang up somehow, but can't find a solution from anyone else who had this problem.

Answer

C.Fasolin picture C.Fasolin · Jul 9, 2017

try this code:

    string filePathNameToMove = "";
    string directoryPathToMove = "";

    if (File.Exists(filePathNameToMove))
    {
        string destinationFilePathName = 
               Path.Combine(directoryPathToMove, Path.GetFileName(filePathNameToMove));
        if (!File.Exists(destinationFilePathName))
        {
            try
            {
                File.Move(filePathNameToMove, destinationFilePathName);
                Console.WriteLine("File Moved!");
            }
            catch (Exception e)
            {
                Console.WriteLine("File Not Moved! Error:" + e.Message);

            }
        }
    }