示例#1
0
        public static async Task <FilesystemResult <BaseStorageFile> > Create(this ShellNewEntry shellEntry, BaseStorageFolder parentFolder, string fileName)
        {
            FilesystemResult <BaseStorageFile> createdFile = null;

            if (!fileName.EndsWith(shellEntry.Extension))
            {
                fileName += shellEntry.Extension;
            }
            if (shellEntry.Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(shellEntry.Template))
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (shellEntry.Data != null)
                {
                    //await FileIO.WriteBytesAsync(createdFile.Result, this.Data); // Calls unsupported OpenTransactedWriteAsync
                    using (var fileStream = await createdFile.Result.OpenStreamForWriteAsync())
                    {
                        await fileStream.WriteAsync(shellEntry.Data, 0, shellEntry.Data.Length);

                        await fileStream.FlushAsync();
                    }
                }
            }
            return(createdFile);
        }
示例#2
0
        public static async Task <TOut> ToStorageItem <TOut>(string path, IShellPage associatedInstance = null) where TOut : IStorageItem
        {
            FilesystemResult <StorageFile>   file   = null;
            FilesystemResult <StorageFolder> folder = null;

            if (associatedInstance == null)
            {
                file = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(path));

                if (!file)
                {
                    folder = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));
                }
            }
            else
            {
                file = await associatedInstance?.FilesystemViewModel?.GetFileFromPathAsync(path);

                if (!file)
                {
                    folder = await associatedInstance?.FilesystemViewModel?.GetFolderFromPathAsync(path);
                }
            }

            if (file)
            {
                return((TOut)(IStorageItem)file.Result);
            }
            else if (folder)
            {
                return((TOut)(IStorageItem)folder.Result);
            }

            return(default(TOut));
        }
示例#3
0
        public async Task <FilesystemResult <StorageFile> > Create(StorageFolder parentFolder, string fileName)
        {
            FilesystemResult <StorageFile> createdFile = null;

            if (!fileName.EndsWith(this.Extension))
            {
                fileName += this.Extension;
            }
            if (Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(Template).AsTask())
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (this.Data != null)
                {
                    await FileIO.WriteBytesAsync(createdFile.Result, this.Data);
                }
            }
            return(createdFile);
        }
示例#4
0
        public static async Task <IStorageItemWithPath> ToStorageItemWithPath(this string path, StorageFolderWithPath parentFolder = null)
        {
            StorageFolderWithPath rootFolder = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            FilesystemResult <StorageFileWithPath> fsFileWithPathResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFileWithPathFromPathAsync(path, rootFolder, parentFolder));
            });

            if (fsFileWithPathResult)
            {
                return(fsFileWithPathResult.Result);
            }

            FilesystemResult <StorageFolderWithPath> fsFolderWithPathResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, rootFolder));
            });

            if (fsFolderWithPathResult)
            {
                return(fsFolderWithPathResult.Result);
            }

            return(null);
        }
        public virtual async void OpenFileLocation(RoutedEventArgs e)
        {
            ShortcutItem item = SlimContentPage.SelectedItem as ShortcutItem;

            if (string.IsNullOrWhiteSpace(item?.TargetPath))
            {
                return;
            }

            // Check if destination path exists
            string folderPath = System.IO.Path.GetDirectoryName(item.TargetPath);
            FilesystemResult <StorageFolderWithPath> destFolder = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(folderPath);

            if (destFolder)
            {
                associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(folderPath), new NavigationArguments()
                {
                    NavPathParam          = folderPath,
                    AssociatedTabInstance = associatedInstance
                });
            }
            else if (destFolder == FileSystemStatusCode.NotFound)
            {
                await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());
            }
            else
            {
                await DialogDisplayHelper.ShowDialogAsync("InvalidItemDialogTitle".GetLocalized(),
                                                          string.Format("InvalidItemDialogContent".GetLocalized(), Environment.NewLine, destFolder.ErrorCode.ToString()));
            }
        }
        public static async void CreateFileFromDialogResultType(AddItemType itemType, ShellNewEntry itemInfo, IShellPage associatedInstance)
        {
            string currentPath = null;

            if (associatedInstance.SlimContentPage != null)
            {
                currentPath = associatedInstance.FilesystemViewModel.WorkingDirectory;
            }

            // Show rename dialog
            DynamicDialog dialog = DynamicDialogFactory.GetFor_RenameDialog();
            await dialog.ShowAsync();

            if (dialog.DynamicResult != DynamicDialogResult.Primary)
            {
                return;
            }

            // Create file based on dialog result
            string userInput = dialog.ViewModel.AdditionalData as string;
            var    folderRes = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(currentPath);

            FilesystemResult created = folderRes;

            if (folderRes)
            {
                switch (itemType)
                {
                case AddItemType.Folder:
                    userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewFolder".GetLocalized();
                    created   = await FilesystemTasks.Wrap(async() =>
                    {
                        return(await associatedInstance.FilesystemHelpers.CreateAsync(
                                   StorageItemHelpers.FromPathAndType(System.IO.Path.Combine(folderRes.Result.Path, userInput), FilesystemItemType.Directory),
                                   true));
                    });

                    break;

                case AddItemType.File:
                    userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : itemInfo?.Name ?? "NewFile".GetLocalized();
                    created   = await FilesystemTasks.Wrap(async() =>
                    {
                        return(await associatedInstance.FilesystemHelpers.CreateAsync(
                                   StorageItemHelpers.FromPathAndType(System.IO.Path.Combine(folderRes.Result.Path, userInput + itemInfo?.Extension), FilesystemItemType.File),
                                   true));
                    });

                    break;
                }
            }
            if (created == FileSystemStatusCode.Unauthorized)
            {
                await DialogDisplayHelper.ShowDialogAsync("AccessDeniedCreateDialog/Title".GetLocalized(), "AccessDeniedCreateDialog/Text".GetLocalized());
            }
        }
示例#7
0
        // TODO: If the TODO of IStorageItemWithPath is implemented, change return type to IStorageItem
        public static async Task <IStorageItem> ToStorageItem(this string path, StorageFolderWithPath parentFolder = null)
        {
            FilesystemResult <StorageFolderWithPath> fsRootFolderResult = await FilesystemTasks.Wrap(async() =>
            {
                return((StorageFolderWithPath)await Path.GetPathRoot(path).ToStorageItemWithPath());
            });

            FilesystemResult <StorageFile> fsFileResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFileFromPathAsync(path, fsRootFolderResult.Result, parentFolder));
            });

            if (fsFileResult)
            {
                if (!string.IsNullOrWhiteSpace(fsFileResult.Result.Path))
                {
                    return(fsFileResult.Result);
                }
                else
                {
                    FilesystemResult <StorageFileWithPath> fsFileWithPathResult = await FilesystemTasks.Wrap(() =>
                    {
                        return(StorageFileExtensions.DangerousGetFileWithPathFromPathAsync(path, fsRootFolderResult));
                    });

                    if (fsFileWithPathResult)
                    {
                        return(null); /* fsFileWithPathResult.Result */ // Could be done if IStorageItemWithPath implemented IStorageItem
                    }
                }
            }

            FilesystemResult <StorageFolder> fsFolderResult = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));

            if (fsFolderResult)
            {
                if (!string.IsNullOrWhiteSpace(fsFolderResult.Result.Path))
                {
                    return(fsFolderResult.Result);
                }
                else
                {
                    FilesystemResult <StorageFolderWithPath> fsFolderWithPathResult = await FilesystemTasks.Wrap(() =>
                    {
                        return(StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, fsRootFolderResult));
                    });

                    if (fsFolderWithPathResult)
                    {
                        return(null); /* fsFolderWithPathResult.Result; */ // Could be done if IStorageItemWithPath implemented IStorageItem
                    }
                }
            }

            return(null);
        }
示例#8
0
        public static async Task <TOut> ToStorageItem <TOut>(string path, IShellPage associatedInstance = null) where TOut : IStorageItem
        {
            FilesystemResult <BaseStorageFile>   file   = null;
            FilesystemResult <BaseStorageFolder> folder = null;

            if (path.ToLower().EndsWith(".lnk") || path.ToLower().EndsWith(".url"))
            {
                // TODO: In the future, when IStorageItemWithPath will inherit from IStorageItem,
                // we could implement this code here for getting .lnk files
                // for now, we can't
                return(default);
示例#9
0
        public static async Task <TRequested> ToStorageItem <TRequested>(string path, IShellPage associatedInstance = null) where TRequested : IStorageItem
        {
            FilesystemResult <BaseStorageFile>   file   = null;
            FilesystemResult <BaseStorageFolder> folder = null;

            if (path.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".url", StringComparison.OrdinalIgnoreCase))
            {
                // TODO: In the future, when IStorageItemWithPath will inherit from IStorageItem,
                // we could implement this code here for getting .lnk files
                // for now, we can't
                return(default);
示例#10
0
        public static async Task PasteItemAsync(string destinationPath, IShellPage associatedInstance)
        {
            FilesystemResult <DataPackageView> packageView = await FilesystemTasks.Wrap(() => Task.FromResult(Clipboard.GetContent()));

            if (packageView && packageView.Result != null)
            {
                await associatedInstance.FilesystemHelpers.PerformOperationTypeAsync(packageView.Result.RequestedOperation, packageView, destinationPath, false, true);

                associatedInstance?.SlimContentPage?.ItemManipulationModel?.RefreshItemsOpacity();
            }
        }
示例#11
0
        public static async Task <FilesystemResult <BaseStorageFile> > Create(this ShellNewEntry shellEntry, BaseStorageFolder parentFolder, string filePath)
        {
            FilesystemResult <BaseStorageFile> createdFile = null;
            var fileName = Path.GetFileName(filePath);

            if (!fileName.EndsWith(shellEntry.Extension, StringComparison.Ordinal))
            {
                fileName += shellEntry.Extension;
            }
            if (shellEntry.Command != null)
            {
                var args = CommandLine.CommandLineParser.SplitArguments(shellEntry.Command);
                if (args.Any())
                {
                    var connection = await AppServiceConnectionHelper.Instance;
                    if (connection != null)
                    {
                        _ = await connection.SendMessageForResponseAsync(new ValueSet()
                        {
                            { "Arguments", "LaunchApp" },
                            { "WorkingDirectory", PathNormalization.GetParentDir(filePath) },
                            { "Application", args[0].Replace("\"", "", StringComparison.Ordinal) },
                            { "Parameters", string.Join(" ", args.Skip(1)).Replace("%1", filePath) }
                        });
                    }
                }
                createdFile = new FilesystemResult <BaseStorageFile>(null, Shared.Enums.FileSystemStatusCode.Success);
            }
            else if (shellEntry.Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(shellEntry.Template))
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (shellEntry.Data != null)
                {
                    //await FileIO.WriteBytesAsync(createdFile.Result, shellEntry.Data); // Calls unsupported OpenTransactedWriteAsync
                    await createdFile.Result.WriteBytesAsync(shellEntry.Data);
                }
            }
            return(createdFile);
        }
示例#12
0
        public static async Task <FilesystemResult <IStorageItem> > ToStorageItemResult(this IStorageItemWithPath item, IShellPage associatedInstance = null)
        {
            var returnedItem = new FilesystemResult <IStorageItem>(null, FileSystemStatusCode.Generic);

            if (!string.IsNullOrEmpty(item.Path))
            {
                returnedItem = (item.ItemType == FilesystemItemType.File) ?
                               ToType <IStorageItem, StorageFile>(associatedInstance != null ?
                                                                  await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(item.Path) :
                                                                  await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(item.Path))) :
                               ToType <IStorageItem, StorageFolder>(associatedInstance != null ?
                                                                    await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(item.Path) :
                                                                    await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(item.Path)));
            }
            if (returnedItem.Result == null && item.Item != null)
            {
                returnedItem = new FilesystemResult <IStorageItem>(item.Item, FileSystemStatusCode.Success);
            }
            return(returnedItem);
        }
        public static async Task <FilesystemResult <BaseStorageFile> > Create(this ShellNewEntry shellEntry, BaseStorageFolder parentFolder, string filePath)
        {
            FilesystemResult <BaseStorageFile> createdFile = null;
            var fileName = Path.GetFileName(filePath);

            if (shellEntry.Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(shellEntry.Template))
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (shellEntry.Data != null)
                {
                    //await FileIO.WriteBytesAsync(createdFile.Result, shellEntry.Data); // Calls unsupported OpenTransactedWriteAsync
                    await createdFile.Result.WriteBytesAsync(shellEntry.Data);
                }
            }
            return(createdFile);
        }
示例#14
0
        /// <summary>
        /// Navigates to a directory or opens file
        /// </summary>
        /// <param name="path">The path to navigate to or open</param>
        /// <param name="associatedInstance">The instance associated with view</param>
        /// <param name="itemType"></param>
        /// <param name="openSilent">Determines whether history of opened item is saved (... to Recent Items/Windows Timeline/opening in background)</param>
        /// <param name="openViaApplicationPicker">Determines whether open file using application picker</param>
        /// <param name="selectItems">List of filenames that are selected upon navigation</param>
        public static async Task <bool> OpenPath(string path, IShellPage associatedInstance, FilesystemItemType?itemType = null, bool openSilent = false, bool openViaApplicationPicker = false, IEnumerable <string> selectItems = null, string args = default)
        {
            string           previousDir    = associatedInstance.FilesystemViewModel.WorkingDirectory;
            bool             isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool             isShortcutItem = path.EndsWith(".lnk") || path.EndsWith(".url"); // Determine
            FilesystemResult opened         = (FilesystemResult)false;

            var shortcutInfo = new ShortcutItem();

            if (itemType == null || isShortcutItem || isHiddenItem)
            {
                if (isShortcutItem)
                {
                    var connection = await AppServiceConnectionHelper.Instance;
                    if (connection == null)
                    {
                        return(false);
                    }
                    var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", path }
                    });

                    if (status == AppServiceResponseStatus.Success)
                    {
                        shortcutInfo.TargetPath           = response.Get("TargetPath", string.Empty);
                        shortcutInfo.Arguments            = response.Get("Arguments", string.Empty);
                        shortcutInfo.WorkingDirectory     = response.Get("WorkingDirectory", string.Empty);
                        shortcutInfo.RunAsAdmin           = response.Get("RunAsAdmin", false);
                        shortcutInfo.PrimaryItemAttribute = response.Get("IsFolder", false) ? StorageItemTypes.Folder : StorageItemTypes.File;

                        itemType = response.Get("IsFolder", false) ? FilesystemItemType.Directory : FilesystemItemType.File;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (isHiddenItem)
                {
                    itemType = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory) ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else
                {
                    itemType = await StorageItemHelpers.GetTypeFromPath(path);
                }
            }

            if (itemType == FilesystemItemType.Library)
            {
                opened = await OpenLibrary(path, associatedInstance, selectItems);
            }
            else if (itemType == FilesystemItemType.Directory)
            {
                opened = await OpenDirectory(path, associatedInstance, selectItems, shortcutInfo);
            }
            else if (itemType == FilesystemItemType.File)
            {
                opened = await OpenFile(path, associatedInstance, selectItems, shortcutInfo, openViaApplicationPicker, args);
            }

            if (opened.ErrorCode == FileSystemStatusCode.NotFound && !openSilent)
            {
                await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());

                associatedInstance.NavToolbarViewModel.CanRefresh = false;
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var ContentOwnedViewModelInstance = associatedInstance.FilesystemViewModel;
                    ContentOwnedViewModelInstance?.RefreshItems(previousDir);
                });
            }

            return(opened);
        }
示例#15
0
        public static async Task CopyItem(IShellPage associatedInstance)
        {
            DataPackage dataPackage = new DataPackage()
            {
                RequestedOperation = DataPackageOperation.Copy
            };
            ConcurrentBag <IStorageItem> items = new ConcurrentBag <IStorageItem>();

            string           copySourcePath = associatedInstance.FilesystemViewModel.WorkingDirectory;
            FilesystemResult result         = (FilesystemResult)false;

            var canFlush = true;

            if (associatedInstance.SlimContentPage.IsItemSelected)
            {
                try
                {
                    await Task.WhenAll(associatedInstance.SlimContentPage.SelectedItems.ToList().Select(async listedItem =>
                    {
                        if (listedItem is FtpItem ftpItem)
                        {
                            canFlush = false;
                            if (listedItem.PrimaryItemAttribute == StorageItemTypes.File)
                            {
                                items.Add(await new FtpStorageFile(ftpItem).ToStorageFileAsync());
                            }
                            else if (listedItem.PrimaryItemAttribute == StorageItemTypes.Folder)
                            {
                                items.Add(new FtpStorageFolder(ftpItem));
                            }
                        }
                        else if (listedItem.PrimaryItemAttribute == StorageItemTypes.File || listedItem is ZipItem)
                        {
                            result = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(listedItem.ItemPath)
                                     .OnSuccess(t => items.Add(t));
                            if (!result)
                            {
                                throw new IOException($"Failed to process {listedItem.ItemPath}.");
                            }
                        }
                        else
                        {
                            result = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(listedItem.ItemPath)
                                     .OnSuccess(t => items.Add(t));
                            if (!result)
                            {
                                throw new IOException($"Failed to process {listedItem.ItemPath}.");
                            }
                        }
                    }));
                }
                catch
                {
                    if (result.ErrorCode == FileSystemStatusCode.Unauthorized)
                    {
                        // Try again with fulltrust process
                        var connection = await AppServiceConnectionHelper.Instance;
                        if (connection != null)
                        {
                            string filePaths = string.Join('|', associatedInstance.SlimContentPage.SelectedItems.Select(x => x.ItemPath));
                            await connection.SendMessageAsync(new ValueSet()
                            {
                                { "Arguments", "FileOperation" },
                                { "fileop", "Clipboard" },
                                { "filepath", filePaths },
                                { "operation", (int)DataPackageOperation.Copy }
                            });
                        }
                    }
                    return;
                }
            }

            var onlyStandard = items.All(x => x is StorageFile || x is StorageFolder || x is SystemStorageFile || x is SystemStorageFolder);

            if (onlyStandard)
            {
                items = new ConcurrentBag <IStorageItem>(await items.ToStandardStorageItemsAsync());
            }
            if (!items.Any())
            {
                return;
            }
            dataPackage.SetStorageItems(items, false);
            try
            {
                Clipboard.SetContent(dataPackage);
                if (onlyStandard && canFlush)
                {
                    Clipboard.Flush();
                }
            }
            catch
            {
                dataPackage = null;
            }
        }
        public static async void CutItem(IShellPage associatedInstance)
        {
            DataPackage dataPackage = new DataPackage
            {
                RequestedOperation = DataPackageOperation.Move
            };
            List <IStorageItem> items  = new List <IStorageItem>();
            FilesystemResult    result = (FilesystemResult)false;

            if (associatedInstance.SlimContentPage.IsItemSelected)
            {
                // First, reset DataGrid Rows that may be in "cut" command mode
                associatedInstance.SlimContentPage.ItemManipulationModel.RefreshItemsOpacity();

                foreach (ListedItem listedItem in associatedInstance.SlimContentPage.SelectedItems)
                {
                    // Dim opacities accordingly
                    listedItem.Opacity = Constants.UI.DimItemOpacity;

                    if (listedItem.PrimaryItemAttribute == StorageItemTypes.File)
                    {
                        result = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(listedItem.ItemPath)
                                 .OnSuccess(t => items.Add(t));

                        if (!result)
                        {
                            break;
                        }
                    }
                    else
                    {
                        result = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(listedItem.ItemPath)
                                 .OnSuccess(t => items.Add(t));

                        if (!result)
                        {
                            break;
                        }
                    }
                }
                if (result.ErrorCode == FileSystemStatusCode.NotFound)
                {
                    associatedInstance.SlimContentPage.ItemManipulationModel.RefreshItemsOpacity();
                    return;
                }
                else if (result.ErrorCode == FileSystemStatusCode.Unauthorized)
                {
                    // Try again with fulltrust process
                    if (associatedInstance.ServiceConnection != null)
                    {
                        string filePaths = string.Join('|', associatedInstance.SlimContentPage.SelectedItems.Select(x => x.ItemPath));
                        AppServiceResponseStatus status = await associatedInstance.ServiceConnection.SendMessageAsync(new ValueSet()
                        {
                            { "Arguments", "FileOperation" },
                            { "fileop", "Clipboard" },
                            { "filepath", filePaths },
                            { "operation", (int)DataPackageOperation.Move }
                        });

                        if (status == AppServiceResponseStatus.Success)
                        {
                            return;
                        }
                    }
                    associatedInstance.SlimContentPage.ItemManipulationModel.RefreshItemsOpacity();
                    return;
                }
            }

            if (!items.Any())
            {
                return;
            }
            dataPackage.SetStorageItems(items);
            try
            {
                Clipboard.SetContent(dataPackage);
                Clipboard.Flush();
            }
            catch
            {
                dataPackage = null;
            }
        }
        public static async void CopyItem(IShellPage associatedInstance)
        {
            DataPackage dataPackage = new DataPackage()
            {
                RequestedOperation = DataPackageOperation.Copy
            };
            List <IStorageItem> items = new List <IStorageItem>();

            string           copySourcePath = associatedInstance.FilesystemViewModel.WorkingDirectory;
            FilesystemResult result         = (FilesystemResult)false;

            if (associatedInstance.SlimContentPage.IsItemSelected)
            {
                foreach (ListedItem listedItem in associatedInstance.SlimContentPage.SelectedItems)
                {
                    if (listedItem.PrimaryItemAttribute == StorageItemTypes.File)
                    {
                        result = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(listedItem.ItemPath)
                                 .OnSuccess(t => items.Add(t));

                        if (!result)
                        {
                            break;
                        }
                    }
                    else
                    {
                        result = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(listedItem.ItemPath)
                                 .OnSuccess(t => items.Add(t));

                        if (!result)
                        {
                            break;
                        }
                    }
                }
                if (result.ErrorCode == FileSystemStatusCode.Unauthorized)
                {
                    // Try again with fulltrust process
                    if (associatedInstance.ServiceConnection != null)
                    {
                        string filePaths = string.Join('|', associatedInstance.SlimContentPage.SelectedItems.Select(x => x.ItemPath));
                        await associatedInstance.ServiceConnection.SendMessageAsync(new ValueSet()
                        {
                            { "Arguments", "FileOperation" },
                            { "fileop", "Clipboard" },
                            { "filepath", filePaths },
                            { "operation", (int)DataPackageOperation.Copy }
                        });
                    }
                    return;
                }
            }

            if (items?.Count > 0)
            {
                dataPackage.SetStorageItems(items);
                try
                {
                    Clipboard.SetContent(dataPackage);
                    Clipboard.Flush();
                }
                catch
                {
                    dataPackage = null;
                }
            }
        }
示例#18
0
        public static async void CutItem(IShellPage associatedInstance)
        {
            DataPackage dataPackage = new DataPackage()
            {
                RequestedOperation = DataPackageOperation.Move
            };
            ConcurrentBag <IStorageItem> items  = new ConcurrentBag <IStorageItem>();
            FilesystemResult             result = (FilesystemResult)false;

            var canFlush = true;

            if (associatedInstance.SlimContentPage.IsItemSelected)
            {
                // First, reset DataGrid Rows that may be in "cut" command mode
                associatedInstance.SlimContentPage.ItemManipulationModel.RefreshItemsOpacity();

                try
                {
                    await Task.WhenAll(associatedInstance.SlimContentPage.SelectedItems.ToList().Select(async listedItem =>
                    {
                        // FTP don't support cut, fallback to copy
                        if (listedItem is not FtpItem)
                        {
                            // Dim opacities accordingly
                            listedItem.Opacity = Constants.UI.DimItemOpacity;
                        }

                        if (listedItem is FtpItem ftpItem)
                        {
                            canFlush = false;
                            if (listedItem.PrimaryItemAttribute == StorageItemTypes.File)
                            {
                                items.Add(await new FtpStorageFile(ftpItem).ToStorageFileAsync());
                            }
                            else if (listedItem.PrimaryItemAttribute == StorageItemTypes.Folder)
                            {
                                items.Add(new FtpStorageFolder(ftpItem));
                            }
                        }
                        else if (listedItem.PrimaryItemAttribute == StorageItemTypes.File || listedItem is ZipItem)
                        {
                            result = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(listedItem.ItemPath)
                                     .OnSuccess(t => items.Add(t));
                            if (!result)
                            {
                                throw new IOException($"Failed to process {listedItem.ItemPath}.");
                            }
                        }
                        else
                        {
                            result = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(listedItem.ItemPath)
                                     .OnSuccess(t => items.Add(t));
                            if (!result)
                            {
                                throw new IOException($"Failed to process {listedItem.ItemPath}.");
                            }
                        }
                    }));
                }
                catch
                {
                    if (result.ErrorCode == FileSystemStatusCode.Unauthorized)
                    {
                        // Try again with fulltrust process
                        var connection = await AppServiceConnectionHelper.Instance;
                        if (connection != null)
                        {
                            string filePaths = string.Join('|', associatedInstance.SlimContentPage.SelectedItems.Select(x => x.ItemPath));
                            AppServiceResponseStatus status = await connection.SendMessageAsync(new ValueSet()
                            {
                                { "Arguments", "FileOperation" },
                                { "fileop", "Clipboard" },
                                { "filepath", filePaths },
                                { "operation", (int)DataPackageOperation.Move }
                            });

                            if (status == AppServiceResponseStatus.Success)
                            {
                                return;
                            }
                        }
                    }
                    associatedInstance.SlimContentPage.ItemManipulationModel.RefreshItemsOpacity();
                    return;
                }
            }

            var onlyStandard = items.All(x => x is StorageFile || x is StorageFolder || x is SystemStorageFile || x is SystemStorageFolder);

            if (onlyStandard)
            {
                items = new ConcurrentBag <IStorageItem>(await items.ToStandardStorageItemsAsync());
            }
            if (!items.Any())
            {
                return;
            }
            dataPackage.SetStorageItems(items, false);
            try
            {
                Clipboard.SetContent(dataPackage);
                if (onlyStandard && canFlush)
                {
                    Clipboard.Flush();
                }
            }
            catch
            {
                dataPackage = null;
            }
        }
示例#19
0
        /// <summary>
        /// Navigates to a directory or opens file
        /// </summary>
        /// <param name="path">The path to navigate to or open</param>
        /// <param name="associatedInstance">The instance associated with view</param>
        /// <param name="itemType"></param>
        /// <param name="openSilent">Determines whether history of opened item is saved (... to Recent Items/Windows Timeline/opening in background)</param>
        /// <param name="openViaApplicationPicker">Determines whether open file using application picker</param>
        /// <param name="selectItems">List of filenames that are selected upon navigation</param>
        public static async Task <bool> OpenPath(string path, IShellPage associatedInstance, FilesystemItemType?itemType = null, bool openSilent = false, bool openViaApplicationPicker = false, IEnumerable <string> selectItems = null)
        // TODO: This function reliability has not been extensively tested
        {
            string           previousDir    = associatedInstance.FilesystemViewModel.WorkingDirectory;
            bool             isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool             isShortcutItem = path.EndsWith(".lnk") || path.EndsWith(".url"); // Determine
            FilesystemResult opened         = (FilesystemResult)false;

            // Shortcut item variables
            string shortcutTargetPath       = null;
            string shortcutArguments        = null;
            string shortcutWorkingDirectory = null;
            bool   shortcutRunAsAdmin       = false;
            bool   shortcutIsFolder         = false;

            if (itemType == null || isShortcutItem || isHiddenItem)
            {
                if (isShortcutItem)
                {
                    var(status, response) = await associatedInstance.ServiceConnection?.SendMessageForResponseAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", path }
                    });

                    if (status == AppServiceResponseStatus.Success)
                    {
                        shortcutTargetPath       = response.Get("TargetPath", string.Empty);
                        shortcutArguments        = response.Get("Arguments", string.Empty);
                        shortcutWorkingDirectory = response.Get("WorkingDirectory", string.Empty);
                        shortcutRunAsAdmin       = response.Get("RunAsAdmin", false);
                        shortcutIsFolder         = response.Get("IsFolder", false);

                        itemType = shortcutIsFolder ? FilesystemItemType.Directory : FilesystemItemType.File;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (isHiddenItem)
                {
                    itemType = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory) ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else
                {
                    itemType = await StorageItemHelpers.GetTypeFromPath(path);
                }
            }

            var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;

            if (itemType == FilesystemItemType.Library) // OpenLibrary
            {
                if (isHiddenItem)
                {
                    associatedInstance.NavigationToolbar.PathControlDisplayText = path;
                    associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                    {
                        NavPathParam          = path,
                        AssociatedTabInstance = associatedInstance
                    });
                    return(true);
                }
                else if (App.LibraryManager.TryGetLibrary(path, out LibraryLocationItem library))
                {
                    opened = (FilesystemResult)await library.CheckDefaultSaveFolderAccess();

                    if (opened)
                    {
                        associatedInstance.NavigationToolbar.PathControlDisplayText = library.Text;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                        {
                            NavPathParam          = path,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems,
                        });
                    }
                }
            }
            else if (itemType == FilesystemItemType.Directory) // OpenDirectory
            {
                if (isShortcutItem)
                {
                    if (string.IsNullOrEmpty(shortcutTargetPath))
                    {
                        await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);

                        return(true);
                    }
                    else
                    {
                        associatedInstance.NavigationToolbar.PathControlDisplayText = shortcutTargetPath;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(shortcutTargetPath), new NavigationArguments()
                        {
                            NavPathParam          = shortcutTargetPath,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems
                        });

                        return(true);
                    }
                }
                else if (isHiddenItem)
                {
                    associatedInstance.NavigationToolbar.PathControlDisplayText = path;
                    associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                    {
                        NavPathParam          = path,
                        AssociatedTabInstance = associatedInstance
                    });

                    return(true);
                }
                else
                {
                    opened = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(path)
                             .OnSuccess(childFolder =>
                    {
                        // Add location to MRU List
                        mostRecentlyUsed.Add(childFolder.Folder, childFolder.Path);
                    });

                    if (!opened)
                    {
                        opened = (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path);
                    }
                    if (!opened)
                    {
                        opened = (FilesystemResult)path.StartsWith("ftp:");
                    }
                    if (opened)
                    {
                        associatedInstance.NavigationToolbar.PathControlDisplayText = path;
                        associatedInstance.NavigateWithArguments(associatedInstance.InstanceViewModel.FolderSettings.GetLayoutType(path), new NavigationArguments()
                        {
                            NavPathParam          = path,
                            AssociatedTabInstance = associatedInstance,
                            SelectItems           = selectItems
                        });
                    }
                }
            }
            else if (itemType == FilesystemItemType.File) // OpenFile
            {
                if (isShortcutItem)
                {
                    if (string.IsNullOrEmpty(shortcutTargetPath))
                    {
                        await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
                    }
                    else
                    {
                        if (!path.EndsWith(".url"))
                        {
                            StorageFileWithPath childFile = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(shortcutTargetPath);

                            if (childFile != null)
                            {
                                // Add location to MRU List
                                mostRecentlyUsed.Add(childFile.File, childFile.Path);
                            }
                        }
                        await Win32Helpers.InvokeWin32ComponentAsync(shortcutTargetPath, associatedInstance, shortcutArguments, shortcutRunAsAdmin, shortcutWorkingDirectory);
                    }
                    opened = (FilesystemResult)true;
                }
                else if (isHiddenItem)
                {
                    await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
                }
                else
                {
                    opened = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(path)
                             .OnSuccess(async childFile =>
                    {
                        // Add location to MRU List
                        mostRecentlyUsed.Add(childFile.File, childFile.Path);

                        if (openViaApplicationPicker)
                        {
                            LauncherOptions options = new LauncherOptions
                            {
                                DisplayApplicationPicker = true
                            };
                            await Launcher.LaunchFileAsync(childFile.File, options);
                        }
                        else
                        {
                            //try using launcher first
                            bool launchSuccess = false;

                            StorageFileQueryResult fileQueryResult = null;

                            //Get folder to create a file query (to pass to apps like Photos, Movies & TV..., needed to scroll through the folder like what Windows Explorer does)
                            StorageFolder currentFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(path));

                            if (currentFolder != null)
                            {
                                QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, null);

                                //We can have many sort entries
                                SortEntry sortEntry = new SortEntry()
                                {
                                    AscendingOrder = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortDirection == Microsoft.Toolkit.Uwp.UI.SortDirection.Ascending
                                };

                                //Basically we tell to the launched app to follow how we sorted the files in the directory.

                                var sortOption = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortOption;

                                switch (sortOption)
                                {
                                case Enums.SortOption.Name:
                                    sortEntry.PropertyName = "System.ItemNameDisplay";
                                    queryOptions.SortOrder.Clear();
                                    queryOptions.SortOrder.Add(sortEntry);
                                    break;

                                case Enums.SortOption.DateModified:
                                    sortEntry.PropertyName = "System.DateModified";
                                    queryOptions.SortOrder.Clear();
                                    queryOptions.SortOrder.Add(sortEntry);
                                    break;

                                case Enums.SortOption.DateCreated:
                                    sortEntry.PropertyName = "System.DateCreated";
                                    queryOptions.SortOrder.Clear();
                                    queryOptions.SortOrder.Add(sortEntry);
                                    break;

                                //Unfortunately this is unsupported | Remarks: https://docs.microsoft.com/en-us/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041
                                //case Enums.SortOption.Size:

                                //sortEntry.PropertyName = "System.TotalFileSize";
                                //queryOptions.SortOrder.Clear();
                                //queryOptions.SortOrder.Add(sortEntry);
                                //break;

                                //Unfortunately this is unsupported | Remarks: https://docs.microsoft.com/en-us/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041
                                //case Enums.SortOption.FileType:

                                //sortEntry.PropertyName = "System.FileExtension";
                                //queryOptions.SortOrder.Clear();
                                //queryOptions.SortOrder.Add(sortEntry);
                                //break;

                                //Handle unsupported
                                default:
                                    //keep the default one in SortOrder IList
                                    break;
                                }

                                fileQueryResult = currentFolder.CreateFileQueryWithOptions(queryOptions);

                                var options = new LauncherOptions
                                {
                                    NeighboringFilesQuery = fileQueryResult
                                };

                                // Now launch file with options.
                                launchSuccess = await Launcher.LaunchFileAsync(childFile.File, options);
                            }

                            if (!launchSuccess)
                            {
                                await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance);
                            }
                        }
                    });
                }
            }

            if (opened.ErrorCode == FileSystemStatusCode.NotFound && !openSilent)
            {
                await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());

                associatedInstance.NavigationToolbar.CanRefresh = false;
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var ContentOwnedViewModelInstance = associatedInstance.FilesystemViewModel;
                    ContentOwnedViewModelInstance?.RefreshItems(previousDir);
                });
            }

            return(opened);
        }
示例#20
0
        public static async Task <TOut> ToStorageItem <TOut>(string path, IShellPage associatedInstance = null) where TOut : IStorageItem
        {
            FilesystemResult <StorageFile>   file   = null;
            FilesystemResult <StorageFolder> folder = null;

            if (path.ToLower().EndsWith(".lnk") || path.ToLower().EndsWith(".url"))
            {
                // TODO: In the future, when IStorageItemWithPath will inherit from IStorageItem,
                //      we could implement this code here for getting .lnk files
                //      for now, we can't

                return(default(TOut));

                if (false) // Prevent unnecessary exceptions
                {
                    Debugger.Break();
                    throw new ArgumentException("Function ToStorageItem<TOut>() does not support converting from .lnk and .url files");
                }
            }

            if (typeof(IStorageFile).IsAssignableFrom(typeof(TOut)))
            {
                await GetFile();
            }
            else if (typeof(IStorageFolder).IsAssignableFrom(typeof(TOut)))
            {
                await GetFolder();
            }
            else if (typeof(IStorageItem).IsAssignableFrom(typeof(TOut)))
            {
                if (System.IO.Path.HasExtension(path)) // Probably a file
                {
                    await GetFile();
                }
                else // Possibly a folder
                {
                    await GetFolder();

                    if (!folder)
                    {
                        // It wasn't a folder, so check file then because it wasn't checked
                        await GetFile();
                    }
                }
            }

            if (file != null && file)
            {
                return((TOut)(IStorageItem)file.Result);
            }
            else if (folder != null && folder)
            {
                return((TOut)(IStorageItem)folder.Result);
            }

            return(default(TOut));

            // Extensions

            async Task GetFile()
            {
                if (associatedInstance == null)
                {
                    file = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(path));
                }
                else
                {
                    file = await associatedInstance?.FilesystemViewModel?.GetFileFromPathAsync(path);
                }
            }

            async Task GetFolder()
            {
                if (associatedInstance == null)
                {
                    folder = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));
                }
                else
                {
                    folder = await associatedInstance?.FilesystemViewModel?.GetFolderFromPathAsync(path);
                }
            }
        }
示例#21
0
 public static FilesystemResult <T> ToType <T, V>(FilesystemResult <V> result) where T : class
 {
     return(new FilesystemResult <T>(result.Result as T, result.ErrorCode));
 }
示例#22
0
        /// <summary>
        /// Navigates to a directory or opens file
        /// </summary>
        /// <param name="path">The path to navigate to or open</param>
        /// <param name="associatedInstance">The instance associated with view</param>
        /// <param name="itemType"></param>
        /// <param name="openSilent">Determines whether history of opened item is saved (... to Recent Items/Windows Timeline/opening in background)</param>
        /// <param name="openViaApplicationPicker">Determines whether open file using application picker</param>
        /// <param name="selectItems">List of filenames that are selected upon navigation</param>
        /// <param name="forceOpenInNewTab">Open folders in a new tab regardless of the "OpenFoldersInNewTab" option</param>
        public static async Task <bool> OpenPath(string path, IShellPage associatedInstance, FilesystemItemType?itemType = null, bool openSilent = false, bool openViaApplicationPicker = false, IEnumerable <string> selectItems = null, string args = default, bool forceOpenInNewTab = false)
        {
            string           previousDir    = associatedInstance.FilesystemViewModel.WorkingDirectory;
            bool             isHiddenItem   = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden);
            bool             isDirectory    = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory);
            bool             isReparsePoint = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.ReparsePoint);
            bool             isShortcutItem = path.EndsWith(".lnk", StringComparison.Ordinal) || path.EndsWith(".url", StringComparison.Ordinal);
            FilesystemResult opened         = (FilesystemResult)false;

            var shortcutInfo = new ShellLinkItem();

            if (itemType == null || isShortcutItem || isHiddenItem || isReparsePoint)
            {
                if (isShortcutItem)
                {
                    var connection = await AppServiceConnectionHelper.Instance;
                    if (connection == null)
                    {
                        return(false);
                    }
                    var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", path }
                    });

                    if (status == AppServiceResponseStatus.Success && response.ContainsKey("ShortcutInfo"))
                    {
                        var shInfo = JsonConvert.DeserializeObject <ShellLinkItem>((string)response["ShortcutInfo"]);
                        if (shInfo != null)
                        {
                            shortcutInfo = shInfo;
                        }
                        itemType = shInfo != null && shInfo.IsFolder ? FilesystemItemType.Directory : FilesystemItemType.File;
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (isReparsePoint)
                {
                    if (!isDirectory)
                    {
                        if (NativeFindStorageItemHelper.GetWin32FindDataForPath(path, out var findData))
                        {
                            if (findData.dwReserved0 == NativeFileOperationsHelper.IO_REPARSE_TAG_SYMLINK)
                            {
                                shortcutInfo.TargetPath = NativeFileOperationsHelper.ParseSymLink(path);
                            }
                        }
                    }
                    itemType ??= isDirectory ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else if (isHiddenItem)
                {
                    itemType = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Directory) ? FilesystemItemType.Directory : FilesystemItemType.File;
                }
                else
                {
                    itemType = await StorageHelpers.GetTypeFromPath(path);
                }
            }

            if (itemType == FilesystemItemType.Library)
            {
                opened = await OpenLibrary(path, associatedInstance, selectItems, forceOpenInNewTab);
            }
            else if (itemType == FilesystemItemType.Directory)
            {
                opened = await OpenDirectory(path, associatedInstance, selectItems, shortcutInfo, forceOpenInNewTab);
            }
            else if (itemType == FilesystemItemType.File)
            {
                opened = await OpenFile(path, associatedInstance, selectItems, shortcutInfo, openViaApplicationPicker, args);
            }

            if (opened.ErrorCode == FileSystemStatusCode.NotFound && !openSilent)
            {
                await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized());

                associatedInstance.ToolbarViewModel.CanRefresh = false;
                associatedInstance.FilesystemViewModel?.RefreshItems(previousDir);
            }

            return(opened);
        }