Example #1
0
 public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
 {
     return(AsyncInfo.Run <BaseStorageFile>(async(cancellationToken) =>
     {
         var destFolder = destinationFolder.AsBaseStorageFolder(); // Avoid calling IStorageFolder method
         var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert());
         using (var inStream = await this.OpenStreamForReadAsync())
             using (var outStream = await destFile.OpenStreamForWriteAsync())
             {
                 await inStream.CopyToAsync(outStream);
                 await outStream.FlushAsync();
             }
         return destFile;
     }));
 }
Example #2
0
 public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
 {
     return(AsyncInfo.Run <BaseStorageFile>(async(cancellationToken) =>
     {
         var destFolder = destinationFolder.AsBaseStorageFolder(); // Avoid calling IStorageFolder method
         if (destFolder is SystemStorageFolder sysFolder)
         {
             // File created by CreateFileAsync will get immediately deleted on MTP?! (#7206)
             return await File.CopyAsync(sysFolder.Folder, desiredNewName, option);
         }
         var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert());
         using (var inStream = await this.OpenStreamForReadAsync())
             using (var outStream = await destFile.OpenStreamForWriteAsync())
             {
                 await inStream.CopyToAsync(outStream);
                 await outStream.FlushAsync();
             }
         return destFile;
     }));
 }
        public async Task <IStorageHistory> MoveAsync(IStorageItemWithPath source,
                                                      string destination,
                                                      NameCollisionOption collision,
                                                      IProgress <float> progress,
                                                      IProgress <FileSystemStatusCode> errorCode,
                                                      CancellationToken cancellationToken)
        {
            if (source.Path == destination)
            {
                progress?.Report(100.0f);
                errorCode?.Report(FileSystemStatusCode.Success);
                return(null);
            }

            if (string.IsNullOrWhiteSpace(source.Path))
            {
                // Can't move (only copy) files from MTP devices because:
                // StorageItems returned in DataPackageView are read-only
                // The item.Path property will be empty and there's no way of retrieving a new StorageItem with R/W access
                return(await CopyAsync(source, destination, collision, progress, errorCode, 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 movedItem = 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 move 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
                {
                    var fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination));

                    if (!fsResult)
                    {
                        Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error());

                        var fsSourceFolder = await source.ToStorageItemResult(associatedInstance);

                        var fsDestinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination));

                        fsResult = fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode;

                        if (fsResult)
                        {
                            var fsResultMove = await FilesystemTasks.Wrap(() => MoveDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, collision.Convert(), true));

                            if (fsResultMove == FileSystemStatusCode.AlreadyExists)
                            {
                                progress?.Report(100.0f);
                                errorCode?.Report(FileSystemStatusCode.AlreadyExists);
                                return(null);
                            }

                            if (fsResultMove)
                            {
                                if (FolderHelpers.CheckFolderForHiddenAttribute(source.Path))
                                {
                                    // The source folder was hidden, apply hidden attribute to destination
                                    NativeFileOperationsHelper.SetFileAttribute(fsResultMove.Result.Path, FileAttributes.Hidden);
                                }
                                movedItem = (StorageFolder)fsResultMove;
                            }
                            fsResult = fsResultMove;
                        }
                        if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly)
                        {
                            fsResult = await PerformAdminOperation(new ValueSet()
                            {
                                { "Arguments", "FileOperation" },
                                { "fileop", "MoveItem" },
                                { "filepath", source.Path },
                                { "destpath", destination },
                                { "overwrite", collision == NameCollisionOption.ReplaceExisting }
                            });
                        }
                    }
                    errorCode?.Report(fsResult.ErrorCode);
                }
            }
            else if (source.ItemType == FilesystemItemType.File)
            {
                var fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination));

                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 fsResultMove = await FilesystemTasks.Wrap(() => file.MoveAsync(destinationResult.Result, Path.GetFileName(file.Name), collision).AsTask());

                        if (fsResultMove == FileSystemStatusCode.AlreadyExists)
                        {
                            progress?.Report(100.0f);
                            errorCode?.Report(FileSystemStatusCode.AlreadyExists);
                            return(null);
                        }

                        if (fsResultMove)
                        {
                            movedItem = file;
                        }
                        fsResult = fsResultMove;
                    }
                    if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly)
                    {
                        fsResult = await PerformAdminOperation(new ValueSet()
                        {
                            { "Arguments", "FileOperation" },
                            { "fileop", "MoveItem" },
                            { "filepath", source.Path },
                            { "destpath", destination },
                            { "overwrite", collision == NameCollisionOption.ReplaceExisting }
                        });
                    }
                }
                errorCode?.Report(fsResult.ErrorCode);
            }

            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> movedListedItems = associatedInstance.FilesystemViewModel.FilesAndFolders
                                                         .Where(listedItem => destination.Contains(listedItem.ItemPath)).ToList();

                    if (movedListedItems.Count > 0)
                    {
                        itemManipulationModel.AddSelectedItems(movedListedItems);
                        itemManipulationModel.FocusSelectedItems();
                    }
                }, Windows.System.DispatcherQueuePriority.Low);
            }

            progress?.Report(100.0f);

            if (collision == NameCollisionOption.ReplaceExisting)
            {
                return(null); // Cannot undo overwrite operation
            }

            var pathWithType = movedItem.FromStorageItem(destination, source.ItemType);

            return(new StorageHistory(FileOperationType.Move, source, pathWithType));
        }
Example #4
0
 public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
 {
     return(AsyncInfo.Run <BaseStorageFile>(async(cancellationToken) =>
     {
         var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath);
         if (hFile.IsInvalid)
         {
             return null;
         }
         using (ZipFile zipFile = new ZipFile(new FileStream(hFile, FileAccess.Read)))
         {
             zipFile.IsStreamOwner = true;
             var znt = new ZipNameTransform(ContainerPath);
             var entry = zipFile.GetEntry(znt.TransformFile(Path));
             if (entry != null)
             {
                 var destFolder = destinationFolder.AsBaseStorageFolder();
                 var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert());
                 using (var inStream = zipFile.GetInputStream(entry))
                     using (var outStream = await destFile.OpenStreamForWriteAsync())
                     {
                         await inStream.CopyToAsync(outStream);
                         await outStream.FlushAsync();
                     }
                 return destFile;
             }
             return null;
         }
     }));
 }
Example #5
0
        public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
        {
            return(AsyncInfo.Run(async(cancellationToken) =>
            {
                using var ftpClient = GetFtpClient();
                if (!await ftpClient.EnsureConnectedAsync())
                {
                    return null;
                }

                BaseStorageFolder destFolder = destinationFolder.AsBaseStorageFolder();
                BaseStorageFile file = await destFolder.CreateFileAsync(desiredNewName, option.Convert());

                var stream = await file.OpenStreamForWriteAsync();
                return await ftpClient.DownloadAsync(stream, FtpPath, token: cancellationToken) ? file : null;
            }));
        }
Example #6
0
        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;
            }));
        }