有没有可能在另一个进程正在使用文件的同时复制该文件?
我之所以问这个问题,是因为当我尝试使用以下代码复制文件时,会引发异常:
System.IO.File.Copy(s, destFile, true);
引发的异常是:
由于另一个进程正在使用文件“D:\ temp \ 1000000045.zip”,因此无法访问该文件。
我不想创建新文件,只是想复制或删除它。这可行吗?
有没有可能在另一个进程正在使用文件的同时复制该文件?
我之所以问这个问题,是因为当我尝试使用以下代码复制文件时,会引发异常:
System.IO.File.Copy(s, destFile, true);
引发的异常是:
由于另一个进程正在使用文件“D:\ temp \ 1000000045.zip”,因此无法访问该文件。
我不想创建新文件,只是想复制或删除它。这可行吗?
一个例子(注:我只是结合了两个 Google 的结果,你可能需要修复一些小错误 )
打开 FileStream 时,关键部分是 FileShare.ReadWrite
。
我使用类似的代码来打开和读取 Excel 文档,而 Excel 仍然处于打开状态并阻止文件。
using (var inputFile = new FileStream(
"oldFile.txt",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using (var outputFile = new FileStream("newFile.txt", FileMode.Create))
{
var buffer = new byte[0x10000];
int bytes;
while ((bytes = inputFile.Read(buffer, 0, buffer.Length)) > 0)
{
outputFile.Write(buffer, 0, bytes);
}
}
}
inputFile.CopyTo(outputFile, 0x10000);
? - Marcel Popescu还有一种选择是使用Process类将锁定的文件复制到其他地方,并调用CMD使用“copy”命令。在大多数情况下,“copy”命令将能够复制文件,即使它正在被另一个进程使用,从而绕过C#File.Copy问题。
示例:
try
{
File.Copy(somefile)
}
catch (IOException e)
{
if (e.Message.Contains("in use"))
{
Process.StartInfo.UseShellExecute = false;
Process.StartInfo.RedirectStandardOutput = true;
Process.StartInfo.FileName = "cmd.exe";
Process.StartInfo.Arguments = "/C copy \"" + yourlockedfile + "\" \"" + destination + "\"";
Process.Start();
Console.WriteLine(Process.StandardOutput.ReadToEnd());
Proess.WaitForExit();
Process.Close();
}
}
the try/catch should be added on top of your current try/catch to handle the file in use exception to allow your code to continue...
var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destFilePath, true);
查找->查找句柄或DLL...
对话框中输入文件名。在搜索结果中,您将能够看到哪个进程正在阻塞您的文件。
您还可以在C#中完成此工作,请参阅:What process locks a file?。不行,有些程序会锁定文件以供读取,如果这样的话,你就无法访问该文件,除非关闭其他程序。
尝试:
var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destinationFilePath, true);