We perform updates of large text files by writing new records to a temp file, then replacing the old file with the temp file. A heavily abbreviated version:
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.