C# 文件已锁定,不允许我复制它
我有一个要备份的文件,我没有任何东西“接触”我“知道”的文件。但我得到的信息是:C# 文件已锁定,不允许我复制它,c#,file-io,file-copying,C#,File Io,File Copying,我有一个要备份的文件,我没有任何东西“接触”我“知道”的文件。但我得到的信息是: "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 =
"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);
源代码:
"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)”,我就会得到错误。是否有“强制”复制的方法?如果其他进程已将文件标记为“已读锁定”,则您将无法复制该文件
最好的办法是找出锁定文件所使用的进程。在尝试复制文件之前,是否在应用程序中创建此文件/写入此文件?如果您确实创建了/写入了它,那么您可能忘记了在此之后关闭它。问题是,您的复制操作的源和目标是相同的。您正在使用路径。组合不正确。从: 如果路径2包含根,则返回路径2 由于在
path2
(第二个参数)中有根,sourceFile
和destFile
都是fileName
的值
您可能想要声明string fileName=“allegro.iliit”
,而不是您所拥有的
显然,异常消息有些误导。我可以读入文件,所以我认为读入然后再写回会有用……是的,如果你能读入,你应该能够做到。下面是一个其他人针对该场景发布的示例:该文件肯定被“某物”劫持了。我确实在记事本++中打开了它,但我关闭了它并在所有地方进行了三次检查……是的,我现在正在查看。我甚至手动创建了一个新文件,不应该让它打开的是来自microsoft的代码