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

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

我认为这是一个非常简单的文件移动器脚本。它检查文件并将其移动到新目录(如果存在):

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

它通过了文件存在的检查,但是在尝试移动它时在下一行中出现错误,指出该文件正在被另一个进程使用。我只能假设 File.Exists 导致它以某种方式挂断,但无法从遇到此问题的任何其他人那里找到解决方案。

试试这个代码:

    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);

            }
        }
    }

以防其他人遇到这个问题。就我而言,该文件已在 Excel 中打开,并且 Excel 在终止后从未被垃圾回收。所以 OS 仍然认为文件正在被访问。我做了以下,粗略的,但它有效。

                for (int i = 1; i > 0; i++)
                {
                     try
                     {
                         File.Move(sourceFileName, destinationFileName);
                         break;
                     } catch
                     {
                         GC.Collect();
                     }
                }