Safe stream update of file
The normal way of avoiding the "delete then move fails problem" is:
- Write to file.new
- Move file.current to file.old
- Move file.new to file.current
- Delete file.new
Then when you come to read, use file.new if file.current is missing, deleting file.old if you see it.
Checking for whether or not the file is available: try opening it for write, but appending to the end. Of course, you'll need to close the handle before you then move it, and in-between someone else could open it - but it would at least be a reasonable optimisation.
Not sure about copying summaries etc, I'm afraid.
Why not try checking the FileAttributes first?
Try something like this:
//If File is readonly
if ( (file.Attribute & System.FileAttributes.ReadOnly) == System.FileAttributes.ReadOnly )
//Don't delete.
Also try using .OpenWrite(). If you can open the file to write to, it is not being accessed and is not currently in use. You can only open a file for writing if its currently in an un-open state. I dont recommend this but it may help you.
FileStream fs = File.OpenWrite(file);
fs.Close();
return false;
You can also use a FileLock checking method. Something like this:
protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
return false;
}
}
catch (IOException)
{
return true;
}
}
you may also want to check FileIOPermission.Write. This allows to see if the file is writable (and able for deletion).
fileIOPerm = New FileIOPermission(FileIOPermissionAccess.Write, FileSpec);
fileIOPerm.Demand();
In regards to question #3 in the original post...You can always move the files to a temp folder, using File.Copy(path1,path2,true). You may want to consider using a temp folder and writing better logic for file manipulation.
If you did decide to use a temp folder, or temp files/intermediate files, then you would also fix your question #2. Try moving the files first.