开发者

.net: Is this file in use?

开发者 https://www.devze.com 2023-02-21 10:25 出处:网络
I\'ve seen multiple version of this question on this site, but none seems to address my precie problem, so here it is:

I've seen multiple version of this question on this site, but none seems to address my precie problem, so here it is:

I'm trying to copy a file, using System.Copy. The destination, if it exists, should be overwritten. I had been using a single line of code for about a month, without problems :

IO.File.Copy(SourceFile, DestFile, True)

But problems started about a week ago, when I started more advanced checks. Partially locked files fail to copy, and the destination gets deleted. Locked files, on the other hand, work correctly: they just trigger a file in use exception.

So I added this line before launching the copy:

Using TestForAccess As New IO.FileStream(SourceFile, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)  : End Using

This was supposed to launch an error if the file was in us开发者_StackOverflowe. But it is to sensitive. Some files (such as thunderbird's abook.mab) trigger an error in this added code, whereas they copied fine before (and you can copy them in explorer).

My question basically is: How do I tell the system: copy source to destination if possible; if not, don't break destination?

Thanks for your help, this thing is driving me nuts.


Use a two step process--copy to a temp file, then rename to destination. That way if the copy fails, the destination file won't be overwritten.

Even better, you four steps. copy to temp, rename dest to other temp, rename temp to dest, delete other temp.

My VB is rusty, but something like this:

Dim DestTemp As String = DestFile + ".temp"
Dim DestBack As String = DestFile + ".bak"
File.Copy(SourceFile, DestTemp, True)
File.Move(DestFile, DestBack)
File.Move(DestTemp, DestFile)
File.Delete(DestBack)


I suspect it's because you're using IO.FileShare.None.

That implies that the file CANNOT be shared by any additional threads. Since the file is already open that will fail, even though a copy would work, since copies usually open a file in READ share mode

You might try IO.FileShare.Read instead.


You need to wrap your code in a try/catch block.

in c# use - you can substitute the exception type with IOException

FileStream fileStream = null;  
try 
{     
fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write); 
} 
catch (UnauthorizedAccessException e) 
{
} 
finally 
{     
if (fileStream != null)         
fileStream.Close (); 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消