文件被锁定了,不让我复制

本文关键字:复制 锁定 文件 | 更新日期: 2023-09-27 18:18:54

我有一个我想要备份的文件,我没有任何"接触"我"知道"的文件。但是我得到的信息是:

"The process cannot access the file 'C:'Cadence'SPB_Data'pcbenv'allegro.ilinit' because it is being used by another process

源代码:

string fileName = @"C:'Cadence'SPB_Data'pcbenv'allegro.ilinit";
string sourcePath = @"C:'Cadence'SPB_Data'pcbenv";
string targetPath = @"C:'Cadence'SPB_Data'pcbenv'backup";
// 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 folder's contents to a new location: 
// Create a new target folder, if necessary. 
if (!System.IO.Directory.Exists(targetPath))
{
    System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and  
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);

所以一旦程序到达这一行" System.IO.File。Copy(sourceFile, destFile, true);我得到了错误。有没有办法"强制"复制

文件被锁定了,不让我复制

在复制之前是否在应用程序中创建/写入该文件?如果你确实创建/写入了它,那么你可能会忘记在此之后关闭它。

问题是复制操作的源和目标是相同的。你使用Path.Combine不正确。来自文档:

如果path2包含根目录,则返回path2。

由于在path2(第二个参数)中有一个根,因此sourceFiledestFile都是fileName的值。

你可能想要声明string fileName = "allegro.ilinit"而不是你所拥有的。

如果其他进程已将该文件标记为"read locked",那么您将无法复制该文件。

最好的办法是使用进程资源管理器找出哪个进程正在锁定文件。