From 89606d3a0572b76895f0ee655087cda68d84daee Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 6 Feb 2015 11:19:52 +1100 Subject: [PATCH] Goes brute force to try to resolve: U4-4049 Some images fail when uploading multiple media files --- src/Umbraco.Core/IO/FileSystemExtensions.cs | 32 +++++++++++++++++++++ src/Umbraco.Web/Editors/MediaController.cs | 7 ++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Core/IO/FileSystemExtensions.cs b/src/Umbraco.Core/IO/FileSystemExtensions.cs index f2152afaab..64dcfc25a0 100644 --- a/src/Umbraco.Core/IO/FileSystemExtensions.cs +++ b/src/Umbraco.Core/IO/FileSystemExtensions.cs @@ -1,10 +1,42 @@ using System; using System.IO; +using System.Threading; namespace Umbraco.Core.IO { public static class FileSystemExtensions { + + /// + /// Attempts to open the file at filePath up to maxRetries times, + /// with a thread sleep time of sleepPerRetryInMilliseconds between retries. + /// + public static FileStream OpenReadWithRetry(this FileInfo file, int maxRetries = 5, int sleepPerRetryInMilliseconds = 50) + { + var retries = maxRetries; + + while (retries > 0) + { + try + { + return File.OpenRead(file.FullName); + } + catch(IOException) + { + retries--; + + if (retries == 0) + { + throw; + } + + Thread.Sleep(sleepPerRetryInMilliseconds); + } + } + + throw new ArgumentException("Retries must be greater than zero"); + } + public static long GetSize(this IFileSystem fs, string path) { using (var file = fs.OpenFile(path)) diff --git a/src/Umbraco.Web/Editors/MediaController.cs b/src/Umbraco.Web/Editors/MediaController.cs index d807d84a26..861750e752 100644 --- a/src/Umbraco.Web/Editors/MediaController.cs +++ b/src/Umbraco.Web/Editors/MediaController.cs @@ -32,6 +32,7 @@ using umbraco; using umbraco.BusinessLogic.Actions; using Constants = Umbraco.Core.Constants; using Umbraco.Core.Configuration; +using Umbraco.Core.Persistence.FaultHandling; namespace Umbraco.Web.Editors { @@ -404,7 +405,11 @@ namespace Umbraco.Web.Editors var mediaService = ApplicationContext.Services.MediaService; var f = mediaService.CreateMedia(fileName, parentId, mediaType); - using (var fs = System.IO.File.OpenRead(file.LocalFileName)) + + var fileInfo = new FileInfo(file.LocalFileName); + var fs = fileInfo.OpenReadWithRetry(); + if (fs == null) throw new InvalidOperationException("Could not acquire file stream"); + using (fs) { f.SetValue(Constants.Conventions.Media.File, fileName, fs); }