Directory.EnumerateFiles 是否锁定了它试图复制的文件?

Is Directory.EnumerateFiles locking the file it is trying to copy?

我正在尝试编写一个程序来将我的 SQL 数据库备份文件复制到 NAS。它以前是工作的,但后来我添加了检查路径是否存在,现在当它试图复制文件时它得到一个异常说 "System.IO.IOException: The process cannot access the file 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\AdventureWorks2012.bak' because it is being used by another process."

我检查了进程资源管理器,没有其他程序正在访问该文件。

我做错了什么?

下面的代码

namespace BackupCopy
{
    class Program
    {
        static void Main(string[] args)
        {
            // Set Source Path
            string sourcePath = @"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup";

            // Verify Source Path Exists
            if (!Directory.Exists(sourcePath))
            {
                Console.WriteLine("Source path does not exist.");
                Console.ReadLine();
                return;
            }



            // Backup each file in Array
            foreach (string filename in Directory.EnumerateFiles(sourcePath))
            {
                Backup(filename);
            }

        }

        public static void Backup(string filename)
        {
            // Pull filename from method input parameter
            string fileName = filename;

            // Set Paths
            string sourcePath = @"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup";
            string targetPath = @"\prometheus\NAS\DB Backups\mercurys";

            // Verify Target Path Exists
            if (!Directory.Exists(targetPath))
            {
                Console.WriteLine("Target path does not exist.");
                Console.ReadLine();
                return;
            }

            // Use Path class to manipulate file and directory paths. 
            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            // To copy a file to another location and  
            // overwrite the destination file if it already exists.
            try
            {
                System.IO.File.Copy(sourceFile, destFile, true);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
                Console.ReadLine();
                return;
            }
        }
    }
}

问题是程序在枚举目录中的文件时锁定了文件句柄。

替换这个;

        // Backup each file in Array
        foreach (string filename in Directory.EnumerateFiles(sourcePath))
        {
            Backup(filename);
        }

有了这个;

        Backup("AdventureWorks2012.bak");

问题解决。