/// <summary> /// Tries to copy the file 'attempts' times /// </summary> /// <param name="file">source file</param> /// <param name="destFileName">Target path and file name</param> /// <param name="attempts">Numbers of times to try coping the file.</param> /// <param name="onError">Action to call on each attempt, passing the throwed exception and the attempt number.</param> /// <returns>Return true or false indicating if the file has been moved.</returns> public static bool tryCopyTo(this FileInfo file, string destFileName, bool overwrite, int attempts, FileOperationAttempDelegate onError = null) { return(prv_tryCopyTo(file, destFileName, overwrite, attempts, onError)); }
private static bool prv_tryFileOperation(Action fileOperationFunction, int attempts, FileOperationAttempDelegate onError = null) { for (int i = 1; i <= attempts; ++i) { try { fileOperationFunction(); return(true); } catch (Exception ex) { onError?.Invoke(ex, i, attempts); } } return(false); }
/// <summary> /// Tries to move the file 'attempts' times /// </summary> /// <param name="file">source file</param> /// <param name="destFileName">Target path and file name</param> /// <param name="attempts">Numbers of times to try moving the file.</param> /// <param name="onError">Action to call on each attempt, passing the throwed exception and the attempt number.</param> /// <returns>Return true or false indicating if the file has been moved.</returns> public static bool tryMoveTo(this FileInfo file, string destFileName, FileOperationAttempDelegate onError = null) { return(prv_tryMoveTo(file, destFileName, DEFAULT_ATTEMPTS, onError)); }
private static bool prv_tryCopyTo(FileInfo file, string destFileName, bool overwrite, int attempts, FileOperationAttempDelegate onError = null) { return(prv_tryFileOperation(() => file.CopyTo(destFileName, overwrite), attempts, onError)); }