/// <summary> /// Perform actual write of binary content to file /// </summary> /// <param name="binary">The binary to store</param> /// <param name="physicalPath">String the file path to write to</param> /// <param name="dimensions">Dimensions of file</param> /// <returns>True is binary was written to disk, false otherwise</returns> private static void WriteBinaryToFile(byte[] binary, string physicalPath, Dimensions dimensions, out MemoryStream memoryStream) { memoryStream = null; if (binary == null) { return; } byte[] buffer = binary; using (new Tracer(binary, physicalPath, dimensions)) { try { if (!File.Exists(physicalPath)) { FileInfo fileInfo = new FileInfo(physicalPath); if (fileInfo.Directory != null && !fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } } if (dimensions != null && (dimensions.Width > 0 || dimensions.Height > 0)) { ImageFormat imgFormat = GetImageFormat(physicalPath); if (imgFormat != null) { buffer = ResizeImage(buffer, dimensions, imgFormat); } } lock (NamedLocker.GetLock(physicalPath)) { using (FileStream fileStream = new FileStream(physicalPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { fileStream.Write(buffer, 0, buffer.Length); } } NamedLocker.RemoveLock(physicalPath); } catch (IOException) { // file possibly accessed by a different thread in a different process, locking failed Log.Warn("Cannot write to {0}. This can happen sporadically, let the next thread handle this.", physicalPath); Thread.Sleep(1000); memoryStream = new MemoryStream(buffer); } } }
private static void CleanupLocalFile(string physicalPath) { using (new Tracer(physicalPath)) { try { // file got unpublished File.Delete(physicalPath); NamedLocker.RemoveLock(physicalPath); } catch (IOException) { // file probabaly accessed by a different thread in a different process Log.Warn("Cannot delete '{0}'. This can happen sporadically, let the next thread handle this.", physicalPath); } } }