/// <summary> /// Deletes a media file. /// </summary> /// <param name="folderPath">The folder path.</param> /// <param name="fileName">The file name.</param> public void DeleteFile(string folderPath, string fileName) { Argument.ThrowIfNullOrEmpty(folderPath, "folderPath"); Argument.ThrowIfNullOrEmpty(fileName, "fileName"); _storageProvider.DeleteFile(_storageProvider.Combine(folderPath, fileName)); }
public MigrateMediaResult MigratAzureBlobStorageToFileSystem(string connectionString, bool isOverwrite) { var mediaItems = _mediaLibraryService.GetMediaContentItems() .List(); var result = new MigrateMediaResult(); var azureFileSystem = InitializeAzureFileSystem(connectionString); foreach (var mediaItem in mediaItems) { var path = Path.Combine(mediaItem.FolderPath, mediaItem.FileName); if (!azureFileSystem.FileExists(path) || (!isOverwrite && _storageProvider.FileExists(path))) { result.IgnoredCount++; continue; } try { if (isOverwrite && _storageProvider.FileExists(path)) { _storageProvider.DeleteFile(path); } var file = _storageProvider.CreateFile(path); var azureFile = azureFileSystem.GetFile(path); using (var inputStream = azureFile.OpenRead()) { using (var outputStream = file.OpenWrite()) { var buffer = new byte[8192]; while (true) { var length = inputStream.Read(buffer, 0, buffer.Length); if (length <= 0) { break; } outputStream.Write(buffer, 0, length); } } } result.SuccessfulTransferCount++; } catch (Exception ex) { Logger.Error(ex, string.Format("Failed to transfer media {0}.", path)); result.UnsuccessfulTransferCount++; _storageProvider.DeleteFile(path); } } return(result); }
private void SaveFilesHelper() { string basePath = @"C:\Users\User\Desktop\beta"; string finalPath = settings.BasePath.Replace("dev", "beta"); if (!_storageProvider.IsFolderExits(finalPath)) { _storageProvider.TryCreateFolder(finalPath); } List <string> files = DirSearch(basePath); foreach (var file in files) { Image image = Image.FromFile(Path.Combine(file), true); var format = image.RawFormat; using (var ms = new MemoryStream()) { image.Save(ms, format); var newPath = file.Replace(@"C:\Users\User\Desktop\beta\userFiles\", ""); if (_storageProvider.IsFileExists(Path.Combine(finalPath, newPath))) { _storageProvider.DeleteFile(Path.Combine(finalPath, newPath)); } _storageProvider.CreateFile(Path.Combine(finalPath, newPath), ms.ToArray()); } } }
public void CreateFileAndDeleteFileTakesAnySlash() { Assert.That(_storageProvider.ListFiles(@"Subfolder1").Count(), Is.EqualTo(2)); var alpha = _storageProvider.CreateFile(@"SubFolder1/alpha.txt"); var beta = _storageProvider.CreateFile(@"SubFolder1\beta.txt"); Assert.That(_storageProvider.ListFiles(@"Subfolder1").Count(), Is.EqualTo(4)); Assert.That(alpha.GetPath(), Is.EqualTo(Path.Combine("SubFolder1", "alpha.txt"))); Assert.That(beta.GetPath(), Is.EqualTo(Path.Combine("SubFolder1", "beta.txt"))); _storageProvider.DeleteFile(@"SubFolder1\alpha.txt"); _storageProvider.DeleteFile(@"SubFolder1/beta.txt"); Assert.That(_storageProvider.ListFiles(@"Subfolder1").Count(), Is.EqualTo(2)); }
static void TestProvider(IStorageProvider provider, string nameProvider) { byte[] buff = new byte[0]; var fileName = pathToTestFile; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); long numBytes = new FileInfo(fileName).Length; buff = br.ReadBytes((int)numBytes); var path = "testfolder\\test.jpeg"; var file = provider.CreateFile(path); var streamWrite = file.OpenWrite(); BinaryWriter bw = new BinaryWriter(streamWrite); bw.Write(buff); Console.WriteLine("********* " + nameProvider + " ****************"); Console.WriteLine("Create file"); if (provider.IsFileExists(path)) { Console.WriteLine("File exist"); } else { Console.WriteLine("File not exist"); } provider.DeleteFile(path); Console.WriteLine("Delete file"); }
public void StorageUniversalTest_SetUp() { SUT = CreateStorage(); TEST_FOLDER = Guid.NewGuid().ToString(); SUT.TryCreateFolder(TEST_FOLDER); SUT.ListFiles(TEST_FOLDER).ToList().ForEach(f => SUT.DeleteFile(f.GetPath())); }
private static void DeleteFile(string fileName, IStorageProvider storageProvider) { // if previous picture is in media storage then delete it if (fileName != null && !fileName.IsWebUrl() && storageProvider.FileExists(fileName)) { storageProvider.DeleteFile(fileName); } }
protected void RemoveMedia(MediaPart part) { if (!string.IsNullOrEmpty(part.FileName)) { var path = _storageProvider.Combine(part.FolderPath, part.FileName); _storageProvider.DeleteFile(path); } }
public void AppendModel(ContentItem c) { var m = c.As <BlockModelPart>(); string statusMessage = ""; bool completed = false; BaseImportTools bit = new BaseImportTools(); string targetFolder; bool attmemptModelLoad; var bmFileName = ExtractBlockModelFromZip(m.BmFileName, out targetFolder, out attmemptModelLoad); IStorageFile bmFile = _storageProvider.GetFile(bmFileName); Stream bmFileStream = bmFile.OpenRead(); ModelImportStatus mos = new ModelImportStatus(); try { // Special append method for GF requirements - contains X, Y, Z, and value to append. // target model must have matching X, Y and Z centroids. // auto generate a format defintion based on Goldfields typical input column data var opts = new TransactionOptions(); opts.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using (new TransactionScope(TransactionScopeOption.Suppress, opts)) { mos = bit.PerformBMAppend(bmFileStream, m.BmGuid, m.Alias, m.ColumnNameToAdd, m.ColumnIndexToAdd, _users.ApplicationConnectionString, ','); mos.importTextFileName = m.BmFileName; mos.targetModelName = m.Alias; } statusMessage += string.Format("Successfully appended data to block model:\n{0} - {1}\n\nFrom file:{2}\n\n", m.Alias, m.BmGuid, m.BmFileName); completed = true; } catch (Exception ex) { statusMessage += string.Format("Error appending data to block model:\n{0} - {1}\n\nFrom file:{2}\n\nError:\n{3}\n\n", m.Alias, m.BmGuid, m.BmFileName, ex.ToString()); } finally { statusMessage += mos.GenerateStringMessage(); bmFileStream.Close(); _storageProvider.DeleteFile(bmFileName); _storageProvider.DeleteFolder(targetFolder); } statusMessage += string.Format("Time Elapsed: {0}\n\n", m.Processed.HasValue ? (DateTime.UtcNow - m.Processed.Value).ToString(@"hh\h\:mm\m\:ss\s\:fff\m\s") : "Unknown"); Logger.Information(statusMessage); _users.EmailUsers(m.Recipients.SplitStringArray(), completed ? "Model Append Succeeded" : "Model Append Failed", statusMessage); }
// This will be called at least by Autofac when the request ends public void Dispose() { if (_isDisposed || !_isAcquired) { return; } _isDisposed = true; // Could throw exception e.g. if the file was deleted. This should not happen. _storageProvider.DeleteFile(MakeFilePath(_name)); }
public bool SaveAvatarFile(int id, Stream stream, string extension) { extension = extension.StripExtension(); var settings = GetSettings(); if (stream.Length > settings.MaxFileSize) { ValidationDictionary.AddError(AvatarsServiceValidationKey.FileTooLarge, T("The file was too large for an avatar ({0}KB), maximum file size is {1}KB", Math.Round((float)(stream.Length / 1024)), Math.Round((float)(settings.MaxFileSize / 1024)))); return(false); } var filePath = GetFilePath(id, extension); if (!IsFileAllowed(filePath)) { ValidationDictionary.AddError(AvatarsServiceValidationKey.NotAllowedFileType, T("This file type is not allowed as an avatar.")); return(false); } // This is the way to overwrite a file... We can't check its existence yet with IStorageProvider, but soon there will be such a method. try { _storageProvider.DeleteFile(filePath); } catch (Exception) { } _storageProvider.SaveStream(filePath, stream); var avatar = _contentManager.Get <AvatarProfilePart>(id); avatar.FileExtension = extension; _contentManager.Flush(); return(true); }
public void SaveSnapshot(Uri uri) { var urlString = uri.ToString(); // This folder will be created before download process will copy files into it var folderPath = _storageProvider.Combine("_ArchivedLinks", urlString.GetHashCode().ToString()); var contentType = GetContentType(uri); var allowableFileContentTypes = new string[] { "application/pdf", "image/jpeg", "image/jpg", "image/png", "image/gif" }; if (allowableFileContentTypes.Contains(contentType)) { DownloadFile(urlString, uri, folderPath, true); } else if (contentType == "text/html") { var htmlWeb = new HtmlWeb(); var document = htmlWeb.Load(urlString); DownloadHtml(ref document, uri, folderPath); htmlWeb.Get(urlString, "/"); var indexPath = _storageProvider.Combine(folderPath, "index.html"); if (_storageProvider.FileExists(indexPath)) { _storageProvider.DeleteFile(indexPath); } using (var stream = _storageProvider.CreateFile(indexPath).OpenWrite()) { document.Save(stream); } } else { throw new NotSupportedException("Uri type not supported"); } }
public static void WriteAllText(this IStorageProvider storageProvider, string path, string contents) { if (storageProvider.FileExists(path)) { storageProvider.DeleteFile(path); } var file = storageProvider.CreateFile(path); using (var stream = file.OpenWrite()) using (var streamWriter = new StreamWriter(stream)) { streamWriter.Write(contents); } }
public void TryDelete(Guid imageId) { try { var extension = MimeTypeMap.List.MimeTypeMap.GetExtension(ApplicationConstants.DefaultMimeType).First(); var imagePath = HttpContext.Current.Server.MapPath(String.Format(ApplicationConstants.ImagePathTemplate, ApplicationConstants.DefaultUserSubDirectory, ReturnSizeSubdirectory(ImageSize.Small), imageId, extension)); _storageProvider.DeleteFile(imagePath); } catch { } }
private void CleanUp() { if (!_storageProvider.FolderExists(WellKnownConstants.LockFileFolder)) { return; } foreach (var file in _storageProvider.ListFiles(WellKnownConstants.LockFileFolder)) { // Removing lock files that weren't touched in two minutes. if (_clock.UtcNow.Subtract(file.GetLastUpdated().ToUniversalTime()).Minutes > 2) { _storageProvider.DeleteFile(file.GetPath()); } } }
static void TestWriteEncryptionProvider(IStorageProvider provider, IStorageEncryptionProvider encryptionProvider, byte[] iv) { byte[] buff = new byte[0]; var fileName = pathToTestFile; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var path = "testfolder\\testencryption990.jpeg"; provider.DeleteFile(path); var file = provider.CreateFile(path); var streamWrite = file.OpenCryptoWrite(encryptionProvider, iv); CopyStream(fs, streamWrite); }
public void Activated() { if (!_storageProvider.FolderExists(WellKnownConstants.LockFileFolder)) { return; } // If there are lock files on shell start older than one minute they were surely created before the shell startup, // thus are remainders of an earlier crash. foreach (var file in _storageProvider.ListFiles(WellKnownConstants.LockFileFolder)) { // Removing lock files that weren't touched in one minute. if (_clock.UtcNow.Subtract(file.GetLastUpdated().ToUniversalTime()).Minutes > 1) { _storageProvider.DeleteFile(file.GetPath()); } } }
public static void ClearDirectory(IStorageProvider provider) { // In this case, since the way we set up the test is different depending on // whether we're using file storage or Azure storage, I'll switch based on what // the provider is. if (provider is FileStorageProvider) { ClearFileStorageDirectory(); return; } photoPath = "originals"; var files = provider.GetFiles(photoPath); foreach (var file in files) { provider.DeleteFile(Path.Combine(photoPath, file)); } }
public static void ClearDirectory(IStorageProvider provider) { // In this case, since the way we set up the test is different depending on // whether we're using file storage or Azure storage, I'll switch based on what // the provider is. if (provider is FileStorageProvider) { ClearFileStorageDirectory(); return; } photoPath = "originals"; var files = provider.GetFiles(photoPath); foreach (var file in files) { provider.DeleteFile(Path.Combine(photoPath, file)); } }
private void DeleteFiles(List <CombinedFileRecord> files) { foreach (var file in files) { _fileRepository.Delete(file); // Try-catch for the case that someone deleted the file. // Currently there is no way to check the existence of a file. try { _storageProvider.DeleteFile(MakePath(file)); } catch (Exception ex) { if (ex.IsFatal()) { throw; } } } }
public static void AnyFiles(IStorageProvider provider) { byte[] buff = new byte[0]; var fileName = @"..\..\TestFile.jpeg"; var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var br = new BinaryReader(fs); long numBytes = new FileInfo(fileName).Length; buff = br.ReadBytes((int)numBytes); var path = "container\\TestFolder\\test.jpeg"; var file = provider.CreateFile(path); var streamWrite = file.OpenWrite(); var bw = new BinaryWriter(streamWrite); bw.Write(buff); Assert.IsTrue(provider.ListFiles("container\\TestFolder\\").Any()); provider.DeleteFile(path); }
public void DeleteFile(string path) { path = new DfsPath(_appConfig.ApplicationName, _appConfig.BucketName, path).ToString(); _service.DeleteFile(path); }
protected override DriverResult Editor(ContentPart part, Fields.FileField field, IUpdateModel updater, dynamic shapeHelper) { var settings = field.PartFieldDefinition.Settings.GetModel <FileFieldSettings>(); var viewModel = new FileFieldViewModel { Settings = settings, Field = field }; if (updater.TryUpdateModel(viewModel, GetPrefix(field, part), null, null)) { var postedFile = ((Controller)updater).Request.Files["FileField-" + field.Name]; AssignDefaultMediaFolder(settings); var mediaFolder = FormatWithTokens(settings.MediaFolder, part.ContentItem.ContentType, field.Name, part.ContentItem.Id); if (postedFile != null && postedFile.ContentLength != 0) { var extension = ParseFileExtenstion(postedFile.FileName); var allowedExtensions = ParseAllowedExtention(settings.ExtenstionsAllowed); var fileName = Path.GetFileNameWithoutExtension(postedFile.FileName); if (allowedExtensions.Contains(extension)) { if (postedFile.ContentLength <= (settings.MaxFileSize * 1024)) { var postedFileLength = postedFile.ContentLength; var postedFileData = new byte[postedFileLength]; var postedFileStream = postedFile.InputStream; postedFileStream.Read(postedFileData, 0, postedFileLength); try { // try to create the folder before uploading a file into it _storageProvider.CreateFolder(mediaFolder); } catch { // the folder can't be created because it already exists, continue } if (settings.NameTag == NameTags.Index) { var lastFileIndex = _storageProvider.ListFiles(mediaFolder) .Count(f => Path.GetFileNameWithoutExtension(f.GetName()).Contains(fileName)); fileName = String.Format("{0} ({1}).{2}", fileName, lastFileIndex + 1, extension); } else if (settings.NameTag == NameTags.TimeStamp) { fileName = String.Format("{0}-{1}.{2}", fileName, DateTime.Now.ToString("yyyyMMddhhmmss"), extension); } // var filePath = _storageProvider.Combine(mediaFolder, fileName); var file = _storageProvider.CreateFile(filePath); using (var fileStream = file.OpenWrite()) { fileStream.Write(postedFileData, 0, postedFileLength); } if (settings.RemovePreviousFileOnUpload && !string.IsNullOrEmpty(field.Path)) { if (_storageProvider.FileExists(field.Path)) { _storageProvider.DeleteFile(field.Path); } } field.Path = _storageProvider.GetPublicUrl(file.GetPath()); } else { updater.AddModelError("File", T("The file size is bigger than the maximum file size, maximum size is {0}KB.", settings.MaxFileSize)); } } else { updater.AddModelError("File", T("The file type is not allowed for {0}.", postedFile.FileName)); } } else { if (settings.Required && string.IsNullOrWhiteSpace(field.Path)) { updater.AddModelError("File", T("You must provide a file for {0}.", field.Name.CamelFriendly())); } } if (string.IsNullOrWhiteSpace(field.Text)) { field.Text = Path.GetFileName(field.Path); } } return(Editor(part, field, shapeHelper)); }
/// <summary> /// Creates an images thumbnail. /// </summary> /// <param name="image">The image full path on the media storage.</param> /// <param name="thumbnailFolderPath">The media path to thumbnails folder.</param> /// <param name="imageName">The image name.</param> /// <param name="thumbnailWidth">The thumbnail width in pixels.</param> /// <param name="thumbnailHeight">The thumbnail height in pixels.</param> /// <param name="keepAspectRatio">Indicates whether to keep the original image aspect ratio</param> /// <param name="expandToFill">Indicates whether to expand the thumbnail to fill the bounds specified by width and height</param> /// <returns>The thumbnail file media path.</returns> protected Thumbnail CreateThumbnail(string image, string thumbnailFolderPath, string imageName, int thumbnailWidth, int thumbnailHeight, bool keepAspectRatio, bool expandToFill) { if (thumbnailWidth <= 0) { throw new ArgumentException("Thumbnail width must be greater than zero", "thumbnailWidth"); } if (thumbnailHeight <= 0) { throw new ArgumentException("Thumbnail height must be greater than zero", "thumbnailHeight"); } string thumbnailFilePath = _storageProvider.Combine(thumbnailFolderPath, imageName); IStorageFile imageFile = _storageProvider.GetFile(image); using (Stream imageStream = imageFile.OpenRead()) { using (Image drawingImage = Image.FromStream(imageStream)) { bool shouldCreateImage = true; // Verify if the image already has a Thumbnail var thumbnailName = _mediaService.GetMediaFiles(thumbnailFolderPath) .Select(o => o.Name).SingleOrDefault(o => o == imageName); if (thumbnailName != null) { // Verify if the existing thumbnail has the correct size (in case the thumbnail settings have been changed) IStorageFile thumbnailFile = _storageProvider.GetFile(thumbnailFilePath); using (Stream thumnailFileStream = thumbnailFile.OpenRead()) { using (Image thumbnailImage = Image.FromStream(thumnailFileStream)) { if (ImageHasCorrectThumbnail(drawingImage, thumbnailImage, thumbnailWidth, thumbnailHeight, keepAspectRatio, expandToFill)) { shouldCreateImage = false; thumbnailWidth = thumbnailImage.Width; thumbnailHeight = thumbnailImage.Height; } } } } if (shouldCreateImage) { using (Image thumbDrawing = CreateThumbnail(drawingImage, thumbnailWidth, thumbnailHeight, keepAspectRatio, expandToFill)) { if (_storageProvider.ListFiles(thumbnailFolderPath).Select(o => o.GetName()).Contains(imageName)) { _storageProvider.DeleteFile(thumbnailFilePath); } IStorageFile thumbFile = _storageProvider.CreateFile(thumbnailFilePath); using (Stream thumbStream = thumbFile.OpenWrite()) { thumbDrawing.Save(thumbStream, _thumbnailImageFormat); thumbnailWidth = thumbDrawing.Width; thumbnailHeight = thumbDrawing.Height; } } } } } string thumbnailPublicUrl = _mediaService.GetMediaPublicUrl(Path.GetDirectoryName(thumbnailFilePath), Path.GetFileName(thumbnailFilePath)); return(new Thumbnail { PublicUrl = thumbnailPublicUrl, Width = thumbnailWidth, Height = thumbnailHeight }); }
public void StorageUniversalTest_TearDown() { SUT.ListFiles(TEST_FOLDER).ToList().ForEach(f => SUT.DeleteFile(f.GetPath())); SUT.DeleteFolder(TEST_FOLDER); }
public void Save(string fingerprint, CombinatorResource resource, ICombinatorSettings settings) { if (settings.EnableResourceSharing && CallOnDefaultShell(cacheFileService => cacheFileService.Save(fingerprint, resource, new CombinatorSettings(settings) { EnableResourceSharing = false }))) { return; } var sliceCount = _fileRepository.Count(file => file.Fingerprint == ConvertFingerprintToStorageFormat(fingerprint)); if (resource.LastUpdatedUtc == DateTime.MinValue) { resource.LastUpdatedUtc = _clock.UtcNow; } // Ceil-ing timestamp to the second, because sub-second precision is not stored in the DB. This would cause a discrepancy between saved // and fetched vs freshly created date times, causing unwanted cache busting for the same resource. resource.LastUpdatedUtc = new DateTime(resource.LastUpdatedUtc.Year, resource.LastUpdatedUtc.Month, resource.LastUpdatedUtc.Day, resource.LastUpdatedUtc.Hour, resource.LastUpdatedUtc.Minute, resource.LastUpdatedUtc.Second); var fileRecord = new CombinedFileRecord() { Fingerprint = ConvertFingerprintToStorageFormat(fingerprint), Slice = ++sliceCount, Type = resource.Type, LastUpdatedUtc = resource.LastUpdatedUtc, Settings = _combinatorResourceManager.SerializeResourceSettings(resource) }; _fileRepository.Create(fileRecord); if (!string.IsNullOrEmpty(resource.Content)) { var path = MakePath(fileRecord); if (_storageProvider.FileExists(path)) { _storageProvider.DeleteFile(path); } using (var stream = _storageProvider.CreateFile(path).OpenWrite()) { var bytes = Encoding.UTF8.GetBytes(resource.Content); stream.Write(bytes, 0, bytes.Length); } if (!resource.IsRemoteStorageResource) { // This is needed to adjust relative paths if the resource is stored in a remote storage provider. // Why the double-saving? Before saving the file there is no reliable way to tell whether the storage public url will be a // remote one or not... var testResource = _combinatorResourceManager.ResourceFactory(resource.Type); testResource.FillRequiredContext("TestCombinedResource", _storageProvider.GetPublicUrl(path)); _combinatorResourceManager.DeserializeSettings(fileRecord.Settings, testResource); testResource.IsRemoteStorageResource = settings.RemoteStorageUrlPattern != null && settings.RemoteStorageUrlPattern.IsMatch(testResource.AbsoluteUrl.ToString()); if (testResource.IsRemoteStorageResource) { _storageProvider.DeleteFile(path); testResource.Content = resource.Content; var relativeUrlsBaseUri = settings.ResourceBaseUri != null ? settings.ResourceBaseUri : new Uri(_urlHelper.RequestContext.HttpContext.Request.Url, _urlHelper.Content("~/")); ResourceProcessingService.RegexConvertRelativeUrlsToAbsolute(testResource, relativeUrlsBaseUri); using (var stream = _storageProvider.CreateFile(path).OpenWrite()) { var bytes = Encoding.UTF8.GetBytes(testResource.Content); stream.Write(bytes, 0, bytes.Length); } resource.IsRemoteStorageResource = true; fileRecord.Settings = _combinatorResourceManager.SerializeResourceSettings(resource); } } } _combinatorEventHandler.BundleChanged(fingerprint); }
public void DeleteFile(string path) { Argument.ThrowIfNullOrEmpty(path, "path"); storageProvider.DeleteFile(path); }
public void StorageUniversalTest_SetUp() { SUT = CreateStorage(); TEST_FOLDER = Guid.NewGuid().ToString(); SUT.TryCreateFolder(TEST_FOLDER); SUT.ListFiles(TEST_FOLDER).ToList().ForEach(f => SUT.DeleteFile(f.GetPath())); }
public bool RemoveFile(string path) { return(_storage.DeleteFile(path)); }