/// <summary>
/// try, try, try... to move this file. tries for a predefined period, in case a very large file was copying, or times out
/// note: blocks thread
/// </summary>
/// <param name="sourcePath">full path to source file</param>
/// <param name="destinationPath">full path to destination file</param>
/// <param name="logFile">log file to write to</param>
/// <returns>true if file moved OK</returns>
public static bool ResilientMoveFile (string sourcePath, string destinationPath, TraceListener logFile)
{
if (logFile != null)
{
logFile.WriteLine ("Moving file '" + sourcePath + "' to '" + destinationPath + "'");
}
// it may have been created, but might not be finished copying. need to wait until we can have accessto move it
bool haveMoved = false;
int tryCount = 0;
DateTime timeStart = DateTime.Now;
while (!haveMoved)
{
// try to get access for predefined period
if (DateTime.Now - timeStart > TimeSpan.FromSeconds (EncoderFolderWatcherService.WatcherSettings.Default.retryFileCopyDurationSeconds))
{
throw new WatcherException (" Failed to get access to '" + sourcePath + "' within established time period -- abandoning");
}
// try renaming file. if we dont have access we will get the IOException
try
{
if (logFile != null)
{
logFile.WriteLine (" Trying to get access to '" + sourcePath + "'");
}
File.Move (sourcePath, destinationPath);
haveMoved = true;
if (logFile != null)
{
logFile.WriteLine (" Moved file '" + sourcePath + "' to '" + destinationPath + "'");
}
}
catch (FileNotFoundException)
{
// source file moved underneath us (someone else claimed?)
if (logFile != null)
{
logFile.WriteLine (" file '" + sourcePath + "' moved from underneath us. This machine should not do the encode");
}
return false;
}
catch (IOException)
{
// did not have access. Wait a little
if (logFile != null)
{
logFile.WriteLine (" Could not get access to '" + sourcePath + "' ... sleeping 1 second before retrying (try " + (++tryCount) + ")");
}
Thread.Sleep (1000);
}
}
return true;
}