private static async Task<StorageFile> SaveFileFromUriAsync(Uri fileUri, string localFileName, string localPath = "Images", NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting) { if (localFileName.StartsWith("/")) localFileName = localFileName.Substring(1); localFileName = Path.GetFileName(localFileName); var destinationFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(localPath, CreationCollisionOption.OpenIfExists); var outFile = await destinationFolder.CreateFileAsync(localFileName, CreationCollisionOption.OpenIfExists); if((await outFile.GetBasicPropertiesAsync()).Size == 0) { BackgroundDownloader backgroundDownloader = new BackgroundDownloader(); var download = backgroundDownloader.CreateDownload(fileUri, outFile); try { download.CostPolicy = BackgroundTransferCostPolicy.Always; var downloadTask = download.StartAsync(); await downloadTask; } catch { } } return outFile; }
private static async Task<StorageFile> SaveFileFromUriAsync(Uri fileUri, string localFileName, string localPath = "Images", NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting) { if (localFileName.StartsWith("/")) localFileName = localFileName.Substring(1); var file = await StorageFile.CreateStreamedFileFromUriAsync(localFileName, fileUri, Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(fileUri)); var destinationFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(localPath, CreationCollisionOption.OpenIfExists); var outFile = await file.CopyAsync(destinationFolder, file.Name, collisionOption); return outFile; }
/// <summary> /// Downloads a file from the specified address and returns the file. /// </summary> /// <param name="fileUri">The URI of the file.</param> /// <param name="folder">The folder to save the file to.</param> /// <param name="fileName">The file name to save the file as.</param> /// <param name="option"> /// A value that indicates what to do /// if the filename already exists in the current folder. /// </param> /// <remarks> /// If no file name is given - the method will try to find /// the suggested file name in the HTTP response /// based on the Content-Disposition HTTP header. /// </remarks> /// <returns></returns> public async static Task<StorageFile> SaveAsync( Uri fileUri, StorageFolder folder = null, string fileName = null, NameCollisionOption option = NameCollisionOption.GenerateUniqueName) { if (folder == null) { folder = ApplicationData.Current.LocalFolder; } var file = await folder.CreateTempFileAsync(); var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload( fileUri, file); var res = await download.StartAsync(); if (string.IsNullOrEmpty(fileName)) { // Use temp file name by default fileName = file.Name; // Try to find a suggested file name in the http response headers // and rename the temp file before returning if the name is found. var info = res.GetResponseInformation(); if (info.Headers.ContainsKey("Content-Disposition")) { var cd = info.Headers["Content-Disposition"]; var regEx = new Regex("filename=\"(?<fileNameGroup>.+?)\""); var match = regEx.Match(cd); if (match.Success) { fileName = match.Groups["fileNameGroup"].Value; await file.RenameAsync(fileName, option); return file; } } } await file.RenameAsync(fileName, option); return file; }
public override async Task <StorageFolder> CopyAsync( StoragePath destinationPath, NameCollisionOption options, CancellationToken cancellationToken = default ) { _ = destinationPath ?? throw new ArgumentNullException(nameof(destinationPath)); if (!EnumInfo.IsDefined(options)) { throw new ArgumentException(ExceptionStrings.Enum.UndefinedValue(options), nameof(options)); } if (!(destinationPath is PhysicalStoragePath)) { throw new ArgumentException( ExceptionStrings.FsCompatibility.StoragePathTypeNotSupported(), nameof(destinationPath) ); } if (destinationPath.FullPath.Parent is null) { throw new IOException(ExceptionStrings.StorageFolder.CannotMoveToRootLocation()); } if (destinationPath.FullPath == _fullPath) { throw new IOException(ExceptionStrings.StorageFolder.CannotCopyToSameLocation()); } var destinationParentFolder = await FsHelper .GetFolderAsync(destinationPath.FullPath.Parent, cancellationToken) .ConfigureAwait(false); var sourceFolder = await FsHelper.GetFolderAsync(_fullPath, cancellationToken).ConfigureAwait(false); await Impl(sourceFolder, destinationParentFolder, destinationPath.FullPath.Name).ConfigureAwait(false); return(FileSystem.GetFolder(destinationPath.FullPath)); async Task Impl(WinStorageFolder src, WinStorageFolder dstFolderParent, string dstFolderName) { var dstFolder = await dstFolderParent .CreateFolderAsync(dstFolderName, ((CreationCollisionOption)options).ToWinOptions()) .AsTask(cancellationToken) .WithConvertedException() .ConfigureAwait(false); foreach (var file in await src.GetFilesAsync().AsAwaitable(cancellationToken)) { await file .CopyAsync(dstFolder, file.Name) .AsTask(cancellationToken) .WithConvertedException() .ConfigureAwait(false); } foreach (var folder in await src.GetFoldersAsync().AsAwaitable(cancellationToken)) { await Impl(folder, dstFolder, folder.Name).ConfigureAwait(false); } } }
private async void PlaylistList_ItemClick(object sender, ItemClickEventArgs e) { PlaylistSongs.Items.Clear(); const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView; Model.Playlist playlistToShow = (Model.Playlist)e.ClickedItem; var fileToShow = fileList.Where(f => f.Name == playlistToShow.Name).FirstOrDefault(); Playlist playlist = await Playlist.LoadAsync(fileToShow); foreach (var s in playlist.Files) { const uint size = 100; using (StorageItemThumbnail thumbnail = await s.GetThumbnailAsync(thumbnailMode, size)) { // Also verify the type is ThumbnailType.Image (album art) instead of ThumbnailType.Icon // (which may be returned as a fallback if the file does not provide album art) if (thumbnail != null && thumbnail.Type == ThumbnailType.Image) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(thumbnail); Model.MediaFile o1 = new Model.AudioFile(); Image i = new Image(); MusicProperties musicProperties = await s.Properties.GetMusicPropertiesAsync(); i.Source = bitmapImage; o1.Thumb = i; o1.Title = s.Name; if (musicProperties.Title != "") { o1.Title = musicProperties.Title; } o1.Name = s.Name; o1.Path = "MusicLibrary"; PlaylistSongs.Items.Add(o1); } } } PlaylistView.Title = fileToShow.Name.Replace(".wpl", ""); ContentDialogResult contentDialogResult = await PlaylistView.ShowAsync(); if (contentDialogResult == ContentDialogResult.Primary) { playlist.Files.Clear(); StorageFolder sf = KnownFolders.MusicLibrary; NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting; PlaylistFormat format = PlaylistFormat.WindowsMedia; foreach (Model.MediaFile item in PlaylistSongs.Items) { StorageFile storageFile = await sf.GetFileAsync(item.Name); playlist.Files.Add(storageFile); Debug.WriteLine(item.Name); } StorageFile savedFile = await playlist.SaveAsAsync(sf, fileToShow.Name.Replace(".wpl", ""), collisionOption, format); } else if (contentDialogResult == ContentDialogResult.Secondary) { if (fileToShow != null) { Playlist playlistToPlay = await Playlist.LoadAsync(fileToShow); MediaPlaybackList mediaPlaybackList = new MediaPlaybackList(); foreach (var f in playlist.Files) { mediaPlaybackList.Items.Add(new MediaPlaybackItem(MediaSource.CreateFromStorageFile(f))); } if (mediaPlaybackList.Items.Count != 0) { mediaElement.Source = mediaPlaybackList; mediaElement.MediaPlayer.Play(); } } } }
internal Task Rename(CancellationToken ct, string desiredName, NameCollisionOption option) => Implementation.RenameAsync(ct, desiredName, option);
public IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) { return null; }
/// <summary> /// Changes folder to new name by adding "_" to its name. /// </summary> /// <param name="fromName">Path to folder.</param> /// <param name="toName"> </param> /// <param name="rootFolder"> </param> /// <param name="option"> </param> /// <returns>Name-changed folder.</returns> public async Task<StorageFolder> ChangeFolderName(string fromName, string toName, StorageFolder rootFolder = null, NameCollisionOption option = NameCollisionOption.ReplaceExisting) { if (string.IsNullOrEmpty(fromName)) { return null; } fromName = NormalizePath(fromName); var changeFolder = rootFolder ?? ApplicationData.Current.LocalFolder; try { changeFolder = await changeFolder.GetFolderAsync(fromName); } catch (Exception) { changeFolder = null; } if (changeFolder != null) { try { if (string.IsNullOrEmpty(toName) || fromName.ToLowerInvariant().EndsWith(toName.ToLowerInvariant())) { return changeFolder; } await changeFolder.RenameAsync(toName, option); } catch (Exception ex) { LogManager.Instance.LogInfo("Cannot change folder name " + fromName + "!" + ex); changeFolder = null; } } return changeFolder; }
/// <summary> /// Extract a zip file. /// </summary> /// <param name="desinationFolder">The destination folder for zip file extraction</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task with a List of strings containing the names of extracted files from the zip archive.</returns> public static async Task <List <string> > ExtractZipAsync(IFile zipFile, IFolder desinationFolder, NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting, CancellationToken cancellationToken = default(CancellationToken)) { var zipFiles = new List <string>(); Stream zipDataStream = await zipFile.OpenAsync(FileAccess.Read, cancellationToken); if (zipDataStream == null) { return(null); } try { ZipArchive zipArchive = new ZipArchive(zipDataStream); foreach (var zipArchiveEntry in zipArchive.Entries) { var zipData = zipArchiveEntry.Open(); if (zipData == null) { } else { if (zipArchiveEntry.Name == null || zipArchiveEntry.Name.Length == 0) { } else { IFile file = await desinationFolder.CreateFileAsync(zipArchiveEntry.Name, CreationCollisionOption.ReplaceExisting); await WriteStreamAsync(file, zipData, cancellationToken); zipFiles.Add(zipArchiveEntry.Name); } } } } catch (Exception e) { } return(zipFiles); }
public IStorageItem Copy(IFolder destinationFolder, string desiredNewName, NameCollisionOption option = NameCollisionOption.FailIfExists) => Copy(destinationFolder.Path, desiredNewName, option);
public IStorageItem Copy(string destinationFolderPath, string desiredNewName, NameCollisionOption option = NameCollisionOption.FailIfExists) => Copy(Combine(destinationFolderPath, desiredNewName), option);
public async Task <IStorageHistory> CopyAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress <float> progress, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken) { return(await CopyItemsAsync(source.CreateEnumerable(), destination.CreateEnumerable(), collision.ConvertBack().CreateEnumerable(), progress, errorCode, cancellationToken)); }
/// <summary> /// Renames a file without changing its location. /// </summary> /// <param name="newName">The new leaf name of the file.</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A task which will complete after the file is renamed. /// </returns> public async Task RenameAsync(string newName, NameCollisionOption collisionOption, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(newName, "newName"); await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); string newPath = PortablePath.Combine(System.IO.Path.GetDirectoryName(_path), newName); await MoveAsync(newPath, collisionOption, cancellationToken); }
/// <summary> /// Renames the current file. /// This method also specifies what to do if an existing item in the current file's location has the same name. /// </summary> /// <param name="desiredName">The desired, new name of the current file. /// <para>If there is an existing item in the current file's location that already has the specified desiredName, the specified <see cref="NameCollisionOption"/> determines how the system responds to the conflict.</para></param> /// <param name="option">The enum value that determines how the system responds if the desiredName is the same as the name of an existing item in the current file's location.</param> /// <returns>No object or value is returned by this method when it completes.</returns> public Task RenameAsync(string desiredName, NameCollisionOption option) { if(string.IsNullOrEmpty(desiredName)) { throw new ArgumentNullException("desiredName"); } #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE return _file.RenameAsync(desiredName, (Windows.Storage.NameCollisionOption)((int)option)).AsTask(); #elif __ANDROID__ || __UNIFIED__ || WIN32 || TIZEN return Task.Run(() => { string folder = global::System.IO.Path.GetDirectoryName(Path); string newPath = global::System.IO.Path.Combine(folder, desiredName); switch(option) { case NameCollisionOption.GenerateUniqueName: string generatedPath = newPath; int num = 2; while(File.Exists(generatedPath)) { generatedPath = global::System.IO.Path.Combine(folder, global::System.IO.Path.GetFileNameWithoutExtension(desiredName), string.Format("({0})", num), global::System.IO.Path.GetExtension(desiredName)); num++; } newPath = generatedPath; break; case NameCollisionOption.ReplaceExisting: if(File.Exists(newPath)) { File.Delete(newPath); } break; default: break; } File.Move(Path, global::System.IO.Path.Combine(global::System.IO.Path.GetDirectoryName(Path), desiredName)); _path = newPath; }); #else throw new PlatformNotSupportedException(); #endif }
public IStorageItem Copy(IFolder destinationFolder, NameCollisionOption option = NameCollisionOption.FailIfExists) => Copy(destinationFolder, Name, option);
public async Task <IStorageHistory> RenameAsync(IStorageItemWithPath source, string newName, NameCollisionOption collision, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken) { if (Path.GetFileName(source.Path) == newName && collision == NameCollisionOption.FailIfExists) { errorCode?.Report(FileSystemStatusCode.AlreadyExists); return(null); } if (!string.IsNullOrWhiteSpace(newName) && !FilesystemHelpers.ContainsRestrictedCharacters(newName) && !FilesystemHelpers.ContainsRestrictedFileName(newName)) { var renamed = await source.ToStorageItemResult(associatedInstance) .OnSuccess(async(t) => { if (t.Name.Equals(newName, StringComparison.CurrentCultureIgnoreCase)) { await t.RenameAsync(newName, NameCollisionOption.ReplaceExisting); } else { await t.RenameAsync(newName, collision); } return(t); }); if (renamed) { errorCode?.Report(FileSystemStatusCode.Success); return(new StorageHistory(FileOperationType.Rename, source, renamed.Result.FromStorageItem())); } else if (renamed == FileSystemStatusCode.Unauthorized) { // Try again with MoveFileFromApp var destination = Path.Combine(Path.GetDirectoryName(source.Path), newName); if (NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination)) { errorCode?.Report(FileSystemStatusCode.Success); return(new StorageHistory(FileOperationType.Rename, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType))); } else { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } else if (renamed == FileSystemStatusCode.NotAFile || renamed == FileSystemStatusCode.NotAFolder) { await DialogDisplayHelper.ShowDialogAsync("RenameError/NameInvalid/Title".GetLocalized(), "RenameError/NameInvalid/Text".GetLocalized()); } else if (renamed == FileSystemStatusCode.NameTooLong) { await DialogDisplayHelper.ShowDialogAsync("RenameError/TooLong/Title".GetLocalized(), "RenameError/TooLong/Text".GetLocalized()); } else if (renamed == FileSystemStatusCode.InUse) { // TODO: proper dialog, retry await DialogDisplayHelper.ShowDialogAsync("FileInUseDeleteDialog/Title".GetLocalized(), ""); } else if (renamed == FileSystemStatusCode.NotFound) { await DialogDisplayHelper.ShowDialogAsync("RenameError/ItemDeleted/Title".GetLocalized(), "RenameError/ItemDeleted/Text".GetLocalized()); } else if (renamed == FileSystemStatusCode.AlreadyExists) { var ItemAlreadyExistsDialog = new ContentDialog() { Title = "ItemAlreadyExistsDialogTitle".GetLocalized(), Content = "ItemAlreadyExistsDialogContent".GetLocalized(), PrimaryButtonText = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(), SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(), CloseButtonText = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized() }; if (UIHelpers.IsAnyContentDialogOpen()) { // Only a single ContentDialog can be open at any time. return(null); } ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { return(await RenameAsync(source, newName, NameCollisionOption.GenerateUniqueName, errorCode, cancellationToken)); } else if (result == ContentDialogResult.Secondary) { return(await RenameAsync(source, newName, NameCollisionOption.ReplaceExisting, errorCode, cancellationToken)); } } errorCode?.Report(renamed); } return(null); }
public abstract void Move(string destinationFullPath, NameCollisionOption option = NameCollisionOption.FailIfExists);
public static async Task <SafeWrapperResult> RenameItem(IStorageItem item, string newName, NameCollisionOption collision = NameCollisionOption.GenerateUniqueName) { SafeWrapperResult result = await SafeWrapperRoutines.SafeWrapAsync(async() => await item.RenameAsync(newName, collision).AsTask()); return(result); }
public abstract void Move(string destinationFolderPath, string desiredNewName, NameCollisionOption option = NameCollisionOption.FailIfExists);
/// <summary> /// Renames a file without changing its location. /// </summary> /// <param name="newName">The new leaf name of the file.</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A task which will complete after the file is renamed. /// </returns> public async Task RenameAsync(string newName, NameCollisionOption collisionOption, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(newName, "newName"); try { await _wrappedFile.RenameAsync(newName, (Windows.Storage.NameCollisionOption)collisionOption).AsTask(cancellationToken).ConfigureAwait(false); } catch (Exception ex) { if (ex.HResult == FILE_ALREADY_EXISTS) { throw new IOException("File already exists.", ex); } throw; } }
public abstract void Move(IFolder destinationFolder, NameCollisionOption option = NameCollisionOption.FailIfExists);
public Windows.Foundation.IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) { throw new NotImplementedException(); }
/// <summary> /// Renames the current item. This method also specifies what to do if an existing /// item in the current item's location has the same name. /// </summary> /// <param name="desiredName">The desired, new name of the current item.</param> /// <param name="option"> /// The <see cref="Enum"/> value that determines how responds if the <see cref="desiredName"/> is the /// same as the name of an existing item in the current item's location. /// Default value is "<see cref="NameCollisionOption.FailIfExists"/>". /// </param> public abstract void Rename(string desiredName, NameCollisionOption option = NameCollisionOption.FailIfExists);
public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { throw new System.NotImplementedException(); }
public async Task <IStorageFile> CopyTo(IStorageFolder folderdestination, string filenamewithextension, NameCollisionOption option) { var status = await new PermissionRequest().Request(); if (!status) { return(null); } if (await Exists()) { string outfilepath = Path.Combine(folderdestination.FullPath, filenamewithextension); if (option == NameCollisionOption.FailIfExists) { if (File.Exists(outfilepath)) { throw new Exception("El archivo que tratas de copiar ya existe"); } } else { if (option == NameCollisionOption.GenerateUniqueName) { outfilepath = Path.Combine(folderdestination.FullPath, UniqueString() + filenamewithextension); } else { File.Delete(outfilepath); } } File.Copy(FullPath, outfilepath); if (File.Exists(outfilepath)) { return(await GetFileFromPath(outfilepath)); } else { throw new FileNotFoundException("No fue posible copiar el archivo"); } } return(null); }
internal Task Move(CancellationToken ct, IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => Implementation.MoveAsync(ct, destinationFolder, desiredNewName, option);
public async Task RenameAsync(string newName, NameCollisionOption collisionOption = NameCollisionOption.FailIfExists, CancellationToken cancellationToken = new CancellationToken()) { throw new NotImplementedException(); }
/// <summary> /// Renames a file without changing its location. /// </summary> /// <param name="newName">The new leaf name of the file.</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A task which will complete after the file is renamed. /// </returns> public async Task RenameAsync(string newName, NameCollisionOption collisionOption, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(newName, "newName"); await MoveAsync(PortablePath.Combine(System.IO.Path.GetDirectoryName(_path), newName), collisionOption, cancellationToken); }
public async Task MoveAsync(string newPath, NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting, CancellationToken cancellationToken = new CancellationToken()) { throw new NotImplementedException(); }
public override async Task <StorageFolder> RenameAsync( string newName, NameCollisionOption options, CancellationToken cancellationToken = default ) { _ = newName ?? throw new ArgumentNullException(nameof(newName)); if (newName.Length == 0) { throw new ArgumentException(ExceptionStrings.String.CannotBeEmpty(), nameof(newName)); } if (newName.Contains(PhysicalPathHelper.InvalidNewNameCharacters)) { throw new ArgumentException( ExceptionStrings.StorageFolder.NewNameContainsInvalidChar(FileSystem.PathInformation), nameof(newName) ); } if (!EnumInfo.IsDefined(options)) { throw new ArgumentException(ExceptionStrings.Enum.UndefinedValue(options), nameof(options)); } var srcFolder = await FsHelper.GetFolderAsync(_fullPath, cancellationToken).ConfigureAwait(false); var fullDestinationPath = _fullParentPath is null ? FileSystem.GetPath(newName).FullPath : _fullParentPath.Join(newName).FullPath; // The Windows Storage API doesn't do a hard replace with the ReplaceExisting option. // For example, if we had this structure: // |_ src // | |_ foo.ext // |_ dst // |_ bar.ext // // and renamed `src` to `dst`, we'd get this result: // |_ dst // |_ foo.ext // |_ bar.ext // // What we (and the spec) want is this: // |_ dst // |_ foo.ext // // We can manually delete the dst folder if it exists to fulfill the specification. // We're *only* doing it if we can be sure that we're not doing an in-place rename though, // i.e. rename `src` to `src`. // Otherwise we'd run into the problem that `src` is deleted and that the rename operation // will fail (DirectoryNotFound). Afterwards the entire folder is gone permanently. // That must be avoided at all cost. if (options == NameCollisionOption.ReplaceExisting && !fullDestinationPath.Name.Equals(_fullPath.Name, FileSystem.PathInformation.DefaultStringComparison)) { try { var dstFolder = await FsHelper.GetFolderAsync(fullDestinationPath, cancellationToken).ConfigureAwait(false); await dstFolder.DeleteAsync(StorageDeleteOption.PermanentDelete).AsAwaitable(cancellationToken); } catch { // If deleting the conflicting folder fails, it's okay, since the whole process // is just there for fulfilling the specification. // The Windows Storage API will still replace conflicting elements. // It's just that certain files may be left over (as described above). // Not fulfilling the spec is the best thing we can do without taking higher risks // of lost data. } } await srcFolder .RenameAsync(newName, options.ToWinOptions()) .AsTask(cancellationToken) .WithConvertedException() .ConfigureAwait(false); return(FileSystem.GetFolder(fullDestinationPath)); }
/// <summary> /// Moves a file. /// </summary> /// <param name="newPath">The new full path of the file.</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A task which will complete after the file is moved. /// </returns> public async Task MoveAsync(string newPath, NameCollisionOption collisionOption, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(newPath, "newPath"); await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); string newDirectory = System.IO.Path.GetDirectoryName(newPath); string newName = System.IO.Path.GetFileName(newPath); for (int counter = 1; ; counter++) { cancellationToken.ThrowIfCancellationRequested(); string candidateName = newName; if (counter > 1) { candidateName = String.Format( CultureInfo.InvariantCulture, "{0} ({1}){2}", System.IO.Path.GetFileNameWithoutExtension(newName), counter, System.IO.Path.GetExtension(newName)); } string candidatePath = PortablePath.Combine(newDirectory, candidateName); if (File.Exists(candidatePath)) { switch (collisionOption) { case NameCollisionOption.FailIfExists: throw new IOException("File already exists."); case NameCollisionOption.GenerateUniqueName: continue; // try again with a new name. case NameCollisionOption.ReplaceExisting: File.Delete(candidatePath); break; } } File.Move(_path, candidatePath); _path = candidatePath; _name = candidateName; return; } }
/// <summary> /// Extract a zip file. /// </summary> /// <param name="desinationFolder">The destination folder for zip file extraction</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task with a List of strings containing the names of extracted files from the zip archive.</returns> public async Task <List <string> > ExtractZipAsync(IFolder desinationFolder, NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting, CancellationToken cancellationToken = default(CancellationToken)) { return(await TargetPlatformFileSystem.ExtractZipAsync(this, desinationFolder, collisionOption, cancellationToken)); }
public async Task <IStorageHistory> CopyAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress <float> progress, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken) { if (associatedInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath)) { errorCode?.Report(FileSystemStatusCode.Unauthorized); progress?.Report(100.0f); // Do not paste files and folders inside the recycle bin await DialogDisplayHelper.ShowDialogAsync( "ErrorDialogThisActionCannotBeDone".GetLocalized(), "ErrorDialogUnsupportedOperation".GetLocalized()); return(null); } IStorageItem copiedItem = null; //long itemSize = await FilesystemHelpers.GetItemSize(await source.ToStorageItem(associatedInstance)); if (source.ItemType == FilesystemItemType.Directory) { if (!string.IsNullOrWhiteSpace(source.Path) && Path.GetDirectoryName(destination).IsSubPathOf(source.Path)) // We check if user tried to copy anything above the source.ItemPath { var destinationName = destination.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); var sourceName = source.Path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); ContentDialog dialog = new ContentDialog() { Title = "ErrorDialogThisActionCannotBeDone".GetLocalized(), Content = $"{"ErrorDialogTheDestinationFolder".GetLocalized()} ({destinationName}) {"ErrorDialogIsASubfolder".GetLocalized()} (sourceName)", //PrimaryButtonText = "ErrorDialogSkip".GetLocalized(), CloseButtonText = "ErrorDialogCancel".GetLocalized() }; ContentDialogResult result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { progress?.Report(100.0f); errorCode?.Report(FileSystemStatusCode.InProgress | FileSystemStatusCode.Success); } else { progress?.Report(100.0f); errorCode?.Report(FileSystemStatusCode.InProgress | FileSystemStatusCode.Generic); } return(null); } else { // CopyFileFromApp only works on file not directories var fsSourceFolder = await source.ToStorageItemResult(associatedInstance); var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); var fsResult = (FilesystemResult)(fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode); if (fsResult) { var fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, collision.Convert())); if (fsCopyResult == FileSystemStatusCode.AlreadyExists) { errorCode?.Report(FileSystemStatusCode.AlreadyExists); progress?.Report(100.0f); return(null); } if (fsCopyResult) { if (FolderHelpers.CheckFolderForHiddenAttribute(source.Path)) { // The source folder was hidden, apply hidden attribute to destination NativeFileOperationsHelper.SetFileAttribute(fsCopyResult.Result.Path, FileAttributes.Hidden); } copiedItem = (StorageFolder)fsCopyResult; } fsResult = fsCopyResult; } errorCode?.Report(fsResult.ErrorCode); if (!fsResult) { return(null); } } } else if (source.ItemType == FilesystemItemType.File) { var fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.CopyFileFromApp(source.Path, destination, true)); if (!fsResult) { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); FilesystemResult <StorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); var sourceResult = await source.ToStorageItemResult(associatedInstance); fsResult = sourceResult.ErrorCode | destinationResult.ErrorCode; if (fsResult) { var file = (StorageFile)sourceResult; var fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), collision).AsTask()); if (fsResultCopy == FileSystemStatusCode.AlreadyExists) { errorCode?.Report(FileSystemStatusCode.AlreadyExists); progress?.Report(100.0f); return(null); } if (fsResultCopy) { copiedItem = fsResultCopy.Result; } fsResult = fsResultCopy; } } errorCode?.Report(fsResult.ErrorCode); if (!fsResult) { return(null); } } if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory) { await Windows.ApplicationModel.Core.CoreApplication.MainView.DispatcherQueue.EnqueueAsync(async() => { await Task.Delay(50); // Small delay for the item to appear in the file list List <ListedItem> copiedListedItems = associatedInstance.FilesystemViewModel.FilesAndFolders .Where(listedItem => destination.Contains(listedItem.ItemPath)).ToList(); if (copiedListedItems.Count > 0) { itemManipulationModel.AddSelectedItems(copiedListedItems); itemManipulationModel.FocusSelectedItems(); } }, Windows.System.DispatcherQueuePriority.Low); } progress?.Report(100.0f); if (collision == NameCollisionOption.ReplaceExisting) { errorCode?.Report(FileSystemStatusCode.Success); return(null); // Cannot undo overwrite operation } var pathWithType = copiedItem.FromStorageItem(destination, source.ItemType); return(new StorageHistory(FileOperationType.Copy, source, pathWithType)); }
public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { return(AsyncInfo.Run(async(cancellationToken) => { using var ftpClient = new FtpClient(); ftpClient.Host = FtpHelpers.GetFtpHost(Path); ftpClient.Port = FtpHelpers.GetFtpPort(Path); ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous); if (!await ftpClient.EnsureConnectedAsync()) { return null; } BaseStorageFolder destFolder = destinationFolder.AsBaseStorageFolder(); BaseStorageFile file = await destFolder.CreateFileAsync(desiredNewName, option.Convert()); var stream = await file.OpenStreamForWriteAsync(); if (await ftpClient.DownloadAsync(stream, FtpPath, token: cancellationToken)) { return file; } return null; })); }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // METHODS ////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public async Task RenameFileAsync(string newName, NameCollisionOption collisionOption) { await ScanFile.RenameAsync(newName, collisionOption); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ScanFile))); }
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => throw new NotSupportedException();
public IAsyncOperation<StorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { throw new NotImplementedException(); }
public virtual async Task RenameAsync(CancellationToken ct, string desiredName, NameCollisionOption option) { var parent = await GetParentAsync(ct); if (parent == null) { throw new InvalidOperationException("The file's parent is not accessible, so we cannot move the file to rename it."); } await MoveAsync(ct, parent, desiredName, option); }
/// <summary> /// Moves a file. /// </summary> /// <param name="newPath">The new full path of the file.</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A task which will complete after the file is moved. /// </returns> public async Task MoveAsync(string newPath, NameCollisionOption collisionOption, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(newPath, "newPath"); var newFolder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(newPath)).AsTask(cancellationToken).ConfigureAwait(false); string newName = System.IO.Path.GetFileName(newPath); try { await _wrappedFile.MoveAsync(newFolder, newName, (Windows.Storage.NameCollisionOption)collisionOption).AsTask(cancellationToken).ConfigureAwait(false); } catch (Exception ex) { if (ex.HResult == FILE_ALREADY_EXISTS) { throw new IOException("File already exists.", ex); } throw; } }
public virtual async Task MoveAsync(CancellationToken ct, IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { var dst = await CreateDestination(ct, destinationFolder, desiredNewName, option); await MoveAndReplaceAsync(ct, dst); }
public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { return null; }
public IAsyncOperation <StorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => AsyncOperation <StorageFile> .FromTask((ct, _) => Implementation.CopyAsync(ct, destinationFolder, desiredNewName, option));
public IAsyncOperation<StorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { return null; }
public IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) => AsyncAction.FromTask(ct => Implementation.RenameAsync(ct, desiredName, option));
public Windows.Foundation.IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { throw new NotImplementedException(); }
public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => AsyncAction.FromTask(ct => Implementation.MoveAsync(ct, destinationFolder, desiredNewName, option));
private static async Task<StorageFile> GenerateResizedImageAsync(StorageFile inputFile, uint width, uint height, uint edgePadding = 5, uint bottomPadding = 20, NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting) { try { string fileName = inputFile.DisplayName + width + "x" + height; string extension = inputFile.Name.Substring(inputFile.Name.LastIndexOf('.')); string folder = inputFile.Path.Substring(0, inputFile.Path.LastIndexOf('\\')); var outputFolder = await StorageFolder.GetFolderFromPathAsync(folder); var newFile = await outputFolder.CreateFileAsync(fileName + extension, CreationCollisionOption.ReplaceExisting); var inputStream = await inputFile.OpenAsync(Windows.Storage.FileAccessMode.Read); var outputStream = await newFile.OpenTransactedWriteAsync(); var inMemStream = new InMemoryRandomAccessStream(); var decoder = await BitmapDecoder.CreateAsync(inputStream); var encoder = await BitmapEncoder.CreateForTranscodingAsync(inMemStream, decoder); // Find aspect ratio for resize float nPercentW = (((float)width - (edgePadding * 2)) / (float)decoder.PixelWidth); float nPercentH = (((float)height - (edgePadding * 2)) / (float)decoder.PixelHeight); float nPercent = nPercentH < nPercentW ? nPercentH : nPercentW; // Scale height and width if (nPercent < 1) { encoder.BitmapTransform.ScaledHeight = (uint)(decoder.PixelHeight * nPercent); encoder.BitmapTransform.ScaledWidth = (uint)(decoder.PixelWidth * nPercent); } // Image may still exceed intended bounds, resize as appropriate if (encoder.BitmapTransform.ScaledWidth > width || encoder.BitmapTransform.ScaledHeight > height) { BitmapBounds bounds = new BitmapBounds(); if (encoder.BitmapTransform.ScaledWidth > width) { bounds.Width = width; bounds.X = (encoder.BitmapTransform.ScaledWidth - width) / 2; } else bounds.Width = encoder.BitmapTransform.ScaledWidth; if (encoder.BitmapTransform.ScaledHeight > height) { bounds.Height = height; bounds.Y = (encoder.BitmapTransform.ScaledHeight - height) / 2; } else bounds.Height = encoder.BitmapTransform.ScaledHeight; encoder.BitmapTransform.Bounds = bounds; } await encoder.FlushAsync(); var outDecoder = await BitmapDecoder.CreateAsync(inMemStream); var outEncoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream.Stream, outDecoder); var transparentBytes = GenerateTransparentBitmap(width, height); PixelDataProvider data = await outDecoder.GetPixelDataAsync(); uint heightOffset = (height - outDecoder.PixelHeight) / 2 - bottomPadding; uint widthOffset = (width - outDecoder.PixelWidth) / 2; byte[] bytes = MergePixelArrays(transparentBytes, width, height, data.DetachPixelData(), outDecoder.PixelWidth, outDecoder.PixelHeight, widthOffset, heightOffset); outEncoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, width, height, 72.0, 72.0, bytes); await outEncoder.FlushAsync(); return newFile; } catch (Exception) { } return null; }
public IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) { throw new System.NotImplementedException(); }