如何复制已在使用的文件

How to Copy a file which is already being used

我在 App_Data 文件夹中有两个文件(.mdf.ldf)。现在我想复制这 2 个文件并需要在 运行 应用程序时粘贴到备份文件夹中。但我收到一个错误:

The process cannot access the file 'D:\App_Data\' because it is being used by another process.

这些是我一直在使用的代码

string dir = Directory.GetDirectories(@"D:\","App_data").FirstOrDefault();
string targetPath = @"D:\Back_up_PayRoll\";

if (System.IO.Directory.Exists(dir))
{
    string[] files = System.IO.Directory.GetFiles(dir);

    if (!Directory.Exists(targetPath))
        Directory.CreateDirectory(targetPath);

    foreach (string s in files)
    {
        var fileName = System.IO.Path.GetFileName(s);

        var destFile = System.IO.Path.Combine(targetPath, fileName);
        System.IO.File.Copy(s, destFile, true);
        MessageBox.Show("BACK-UP Done..");
    }
}

如果系统可用,您可以使用 Volume Shadow Copy Service

的快照

在 C# 中,有包装 COM 接口的方便的 AlphaVSS 库,但您可以直接实现它。

如果 VSS 不可用,那就是运气不好,无法绕过文件锁定

PS:当然,这不像File.Copy

那么简单

如果不先断开 MDF 文件,则无法以任何方式访问它。

最好的办法是使用 SQL 备份它,或者关闭您的应用程序并通过 运行 BAT 文件

复制它