SetAttributes only works with a sleep

B

BrianB

I have this code.

If File.Exists(strsource) Then
If File.Exists(strDest) Then
Exit Function
End If
Call File.Copy(strsource, strDest, Me.Overwrite)
If File.Exists(strDest) Then
Try
File.SetAttributes(strDest, FileAttributes.Normal)
Catch ex As Exception
msgbox(ex.GetBaseException.ToString)
End Try
End If
End If

All the strsource files are read-only. The SetAttributes command is supposed
to remove that read-only on the copied file. Most of the time it works, but
occasionally it does not. All of the strsource files have the same owner and
permission values.

If, after the File.Copy I have the program sleep for 2-3 seconds for each
file, then the read-only attribute is successfully cleared for all files.
Obviously this solution kills performance. Any ideas what is happening and
how to solve it without the Sleep?

Brian
 
S

saberman

File.Copy returns before the target system completes writting the data to the
physical drive so the file is still in use.

I do not believe there is anyway, includng a filesystem watcher, to wait for
the file to complete the transfer.

You have two choices:

1. Write your own file copy routine that forces the output buffers to be
flushed to the target drive.

2. Modify your code to include a loop with a sleep in it:

Change:
Try
File.SetAttributes(strDest, FileAttributes.Normal)
Catch ex As Exception
msgbox(ex.GetBaseException.ToString)
End Try
to
Do while (true)
Try
File.SetAttributes(strDest, FileAttributes.Normal)
Exit Do
Catch ex As Exception
Thread.Sleep(100)
End Try
Loop
You may also want to put in a check that the thrown exception is because the
file is being used by another process and rethrow any other exception.
 
B

BrianB

Thank you. One thing that I should mention is that the SetAttributes call
does not throw an exception even when it does not work.

Brian
 
S

Stewart Berman

Then use a File.Move(strDist,strDisk) to test. It will throw an exception if the file is in use but
not throw one if it is available. Put it before the SetAttributes call.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top