private async void RecentsView_ItemClick(object sender, ItemClickEventArgs e) { var path = (e.ClickedItem as RecentItem).RecentPath; try { await Interaction.InvokeWin32Component(path); } catch (UnauthorizedAccessException) { await App.ConsentDialogDisplay.ShowAsync(); } catch (ArgumentException) { if (new DirectoryInfo(path).Root.ToString().Contains(@"C:\")) { App.CurrentInstance.ContentFrame.Navigate(App.AppSettings.GetLayoutType(), path); } else { foreach (DriveItem drive in App.AppSettings.DrivesManager.Drives) { if (drive.Path.ToString() == new DirectoryInfo(path).Root.ToString()) { App.CurrentInstance.ContentFrame.Navigate(App.AppSettings.GetLayoutType(), path); return; } } } } catch (COMException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("DriveUnpluggedDialog.Title"), ResourceController.GetTranslation("DriveUnpluggedDialog.Text")); } }
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 void PrintDocument(object toPrint) { var data = toPrint as DataGrid; if (data.Items.Count != 0) { DialogDisplayHelper.DisplayMessageBox("no printer found", "information", boxIcon: MessageBoxImage.Error); return; } DialogDisplayHelper.DisplayMessageBox("Nothing have selected to print", "Information", boxIcon: MessageBoxImage.Warning); }
public static async void CreateFile(AddItemType itemType) { string currentPath = null; if (App.CurrentInstance.ContentPage != null) { currentPath = App.CurrentInstance.FilesystemViewModel.WorkingDirectory; } StorageFolderWithPath folderWithPath = await ItemViewModel.GetFolderWithPathFromPathAsync(currentPath); StorageFolder folderToCreateItem = folderWithPath.Folder; // Show rename dialog RenameDialog renameDialog = new RenameDialog(); var renameResult = await renameDialog.ShowAsync(); if (renameResult != ContentDialogResult.Primary) { return; } // Create file based on dialog result string userInput = renameDialog.storedRenameInput; try { switch (itemType) { case AddItemType.Folder: userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewFolder".GetLocalized(); await folderToCreateItem.CreateFolderAsync(userInput, CreationCollisionOption.GenerateUniqueName); break; case AddItemType.TextDocument: userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewTextDocument".GetLocalized(); await folderToCreateItem.CreateFileAsync(userInput + ".txt", CreationCollisionOption.GenerateUniqueName); break; case AddItemType.BitmapImage: userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewBitmapImage".GetLocalized(); await folderToCreateItem.CreateFileAsync(userInput + ".bmp", CreationCollisionOption.GenerateUniqueName); break; } } catch (UnauthorizedAccessException) { await DialogDisplayHelper.ShowDialog("AccessDeniedCreateDialog/Title".GetLocalized(), "AccessDeniedCreateDialog/Text".GetLocalized()); } }
private void AddUpdate(object data) { var havePassword = data as IHavePassword; if (havePassword.SecureString.ComparePassword(havePassword.SecureString1, out string password)) { var response = WebConnect.PostData("User/Create", new User { Name = Name, Uname = UserName, Password = password, UserId = flag ? 0 : LogInFor.User.UserId }); DialogDisplayHelper.DisplayMessageBox(flag?"Add Complete":"Update Complete", "Informative"); } else { DialogDisplayHelper.DisplayMessageBox("Confirm Password And Password Not Matched", "Informative", MessageBoxButton.OK, MessageBoxImage.Warning); } }
private async void RecentFilesWidget_RecentFileInvoked(object sender, UserControls.PathNavigationEventArgs e) { try { var directoryName = Path.GetDirectoryName(e.ItemPath); await AppInstance.InteractionOperations.InvokeWin32ComponentAsync(e.ItemPath, workingDir : directoryName); } catch (UnauthorizedAccessException) { var consentDialog = new ConsentDialog(); await consentDialog.ShowAsync(); } catch (ArgumentException) { if (new DirectoryInfo(e.ItemPath).Root.ToString().Contains(@"C:\")) { AppInstance.ContentFrame.Navigate(FolderSettings.GetLayoutType(e.ItemPath), new NavigationArguments() { AssociatedTabInstance = AppInstance, NavPathParam = e.ItemPath }); } else { foreach (DriveItem drive in Enumerable.Concat(App.DrivesManager.Drives, AppSettings.CloudDrivesManager.Drives)) { if (drive.Path.ToString() == new DirectoryInfo(e.ItemPath).Root.ToString()) { AppInstance.ContentFrame.Navigate(FolderSettings.GetLayoutType(e.ItemPath), new NavigationArguments() { AssociatedTabInstance = AppInstance, NavPathParam = e.ItemPath }); return; } } } } catch (COMException) { await DialogDisplayHelper.ShowDialogAsync( "DriveUnpluggedDialog/Title".GetLocalized(), "DriveUnpluggedDialog/Text".GetLocalized()); } }
private void ActivateTrain(object obj) { if (obj == null || Action.Equals("SelectAction") || Direction.Equals("SelectDirection")) { return; } var data = obj as InactiveTrains; var response = WebConnect.UpdateDate("Train/AddTranToWatch", new { TrainId = data.TID, Status = Action, Direction = Direction.Equals("UpWay") }); if (response.StatusCode == HttpStatusCode.OK) { GetData(); DialogDisplayHelper.DisplayMessageBox("Activation Completed", "Informative"); } else if (response.StatusCode == HttpStatusCode.BadRequest) { DialogDisplayHelper.DisplayMessageBox("Configuration Error Occur Check System Configurations", "System Error Detection", boxIcon: MessageBoxImage.Warning); } Action = "SelectAction"; Direction = "SelectDirection"; }
public async void ToggleQuickLook() { try { if (CurrentInstance.ContentPage.IsItemSelected && !App.CurrentInstance.ContentPage.isRenamingItem) { var clickedOnItem = CurrentInstance.ContentPage.SelectedItem; Debug.WriteLine("Toggle QuickLook"); ApplicationData.Current.LocalSettings.Values["path"] = clickedOnItem.ItemPath; ApplicationData.Current.LocalSettings.Values["Arguments"] = "ToggleQuickLook"; await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } } catch (FileNotFoundException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("FileNotFoundDialog.Title"), ResourceController.GetTranslation("FileNotFoundPreviewDialog.Text")); NavigationActions.Refresh_Click(null, null); } }
private async Task ImportSettings() { FileOpenPicker filePicker = new FileOpenPicker(); filePicker.FileTypeFilter.Add(Path.GetExtension(Constants.LocalSettings.UserSettingsFileName)); StorageFile file = await filePicker.PickSingleFileAsync(); if (file != null) { try { string import = await FileIO.ReadTextAsync(file); UserSettingsService.ImportSettings(import); } catch { UIHelpers.CloseAllDialogs(); await DialogDisplayHelper.ShowDialogAsync("SettingsImportErrorTitle".GetLocalized(), "SettingsImportErrorDescription".GetLocalized()); } } }
private async void RemoveOneFrequentItem(object sender, RoutedEventArgs e) { // Get the sender frameworkelement if (sender is MenuFlyoutItem fe) { // Grab it's datacontext ViewModel and remove it from the list. if (fe.DataContext is RecentItem vm) { if (await DialogDisplayHelper.ShowDialog("Remove item from Recents List", "Do you wish to remove " + vm.Name + " from the list?", "Yes", "No")) { // remove it from the visible collection recentItemsCollection.Remove(vm); // Now clear it also from the recent list cache permanently. // No token stored in the viewmodel, so need to find it the old fashioned way. var mru = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; foreach (var element in mru.Entries) { var f = await mru.GetItemAsync(element.Token); if (f.Path == vm.RecentPath || element.Metadata == vm.RecentPath) { mru.Remove(element.Token); if (recentItemsCollection.Count == 0) { Empty.Visibility = Visibility.Visible; } break; } } } } } }
public async Task <IStorageHistory> DeleteAsync(IStorageItemWithPath source, IProgress <float> progress, IProgress <FilesystemErrorCode> errorCode, bool permanently, CancellationToken cancellationToken) { bool deleteFromRecycleBin = recycleBinHelpers.IsPathUnderRecycleBin(source.Path); FilesystemResult fsResult = FilesystemErrorCode.ERROR_INPROGRESS; errorCode?.Report(fsResult); progress?.Report(0.0f); if (source.ItemType == FilesystemItemType.File) { fsResult = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(source.Path) .OnSuccess((t) => t.DeleteAsync(permanently ? StorageDeleteOption.PermanentDelete : StorageDeleteOption.Default).AsTask()); } else if (source.ItemType == FilesystemItemType.Directory) { fsResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(source.Path) .OnSuccess((t) => t.DeleteAsync(permanently ? StorageDeleteOption.PermanentDelete : StorageDeleteOption.Default).AsTask()); } errorCode?.Report(fsResult); if (fsResult == FilesystemErrorCode.ERROR_UNAUTHORIZED) { // Try again with fulltrust process if (associatedInstance.FilesystemViewModel.Connection != null) { AppServiceResponse response = await associatedInstance.FilesystemViewModel.Connection.SendMessageAsync(new ValueSet() { { "Arguments", "FileOperation" }, { "fileop", "DeleteItem" }, { "filepath", source.Path }, { "permanently", permanently } }); fsResult = (FilesystemResult)(response.Status == AppServiceResponseStatus.Success && response.Message.Get("Success", false)); } } else if (fsResult == FilesystemErrorCode.ERROR_INUSE) { // TODO: retry or show dialog await DialogDisplayHelper.ShowDialogAsync("FileInUseDeleteDialog/Title".GetLocalized(), "FileInUseDeleteDialog/Text".GetLocalized()); } if (deleteFromRecycleBin) { // Recycle bin also stores a file starting with $I for each item string iFilePath = Path.Combine(Path.GetDirectoryName(source.Path), Path.GetFileName(source.Path).Replace("$R", "$I")); await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(iFilePath) .OnSuccess(t => t.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask()); } errorCode?.Report(fsResult); progress?.Report(100.0f); if (fsResult) { await associatedInstance.FilesystemViewModel.RemoveFileOrFolderAsync(source.Path); if (!permanently) { // Enumerate Recycle Bin List <ShellFileItem> items = await recycleBinHelpers.EnumerateRecycleBin(); List <ShellFileItem> nameMatchItems = new List <ShellFileItem>(); // Get name matching files if (items != null) { if (Path.GetExtension(source.Path) == ".lnk" || Path.GetExtension(source.Path) == ".url") // We need to check if it is a shortcut file { nameMatchItems = items.Where((item) => item.FilePath == Path.Combine(Path.GetDirectoryName(source.Path), Path.GetFileNameWithoutExtension(source.Path))).ToList(); } else { nameMatchItems = items.Where((item) => item.FilePath == source.Path).ToList(); } } // Get newest file ShellFileItem item = nameMatchItems.Where((item) => item.RecycleDate != null).OrderBy((item) => item.RecycleDate).FirstOrDefault(); return(new StorageHistory(FileOperationType.Recycle, source, StorageItemHelpers.FromPathAndType(item?.RecyclePath, source.ItemType))); } return(new StorageHistory(FileOperationType.Delete, source, null)); } else { // Stop at first error return(null); } }
public async Task <IStorageHistory> CopyAsync(IStorageItemWithPath source, string destination, IProgress <float> progress, IProgress <FilesystemErrorCode> errorCode, CancellationToken cancellationToken) { if (associatedInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath)) { errorCode?.Report(FilesystemErrorCode.ERROR_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(FilesystemErrorCode.ERROR_INPROGRESS | FilesystemErrorCode.ERROR_SUCCESS); } else { progress?.Report(100.0f); errorCode?.Report(FilesystemErrorCode.ERROR_INPROGRESS | FilesystemErrorCode.ERROR_GENERIC); } return(null); } else { 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, CreationCollisionOption.FailIfExists)); if (fsCopyResult == FilesystemErrorCode.ERROR_ALREADYEXIST) { var ItemAlreadyExistsDialog = new ContentDialog() { Title = "ItemAlreadyExistsDialogTitle".GetLocalized(), Content = "ItemAlreadyExistsDialogContent".GetLocalized(), PrimaryButtonText = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(), SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(), CloseButtonText = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized() }; ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, CreationCollisionOption.GenerateUniqueName)); } else if (result == ContentDialogResult.Secondary) { fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, CreationCollisionOption.ReplaceExisting)); return(null); // Cannot undo overwrite operation } else { return(null); } } if (fsCopyResult) { if (associatedInstance.FilesystemViewModel.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) { FilesystemResult <StorageFolder> destinationResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); var sourceResult = await source.ToStorageItemResult(associatedInstance); var fsResult = (FilesystemResult)(sourceResult.ErrorCode | destinationResult.ErrorCode); if (fsResult) { var file = (StorageFile)sourceResult; var fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.FailIfExists).AsTask()); if (fsResultCopy == FilesystemErrorCode.ERROR_ALREADYEXIST) { var ItemAlreadyExistsDialog = new ContentDialog() { Title = "ItemAlreadyExistsDialogTitle".GetLocalized(), Content = "ItemAlreadyExistsDialogContent".GetLocalized(), PrimaryButtonText = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(), SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(), CloseButtonText = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized() }; ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.GenerateUniqueName).AsTask()); } else if (result == ContentDialogResult.Secondary) { fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.ReplaceExisting).AsTask()); return(null); // Cannot undo overwrite operation } else { return(null); } } if (fsResultCopy) { copiedItem = fsResultCopy.Result; } fsResult = fsResultCopy; } if (fsResult == FilesystemErrorCode.ERROR_UNAUTHORIZED || fsResult == FilesystemErrorCode.ERROR_GENERIC) { // Try again with CopyFileFromApp if (NativeFileOperationsHelper.CopyFileFromApp(source.Path, destination, true)) { fsResult = (FilesystemResult)true; } else { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } errorCode?.Report(fsResult.ErrorCode); if (!fsResult) { return(null); } } if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory) { if (copiedItem != null) { List <ListedItem> copiedListedItems = associatedInstance.FilesystemViewModel.FilesAndFolders .Where(listedItem => copiedItem.Path.Contains(listedItem.ItemPath)).ToList(); if (copiedListedItems.Count > 0) { associatedInstance.ContentPage.AddSelectedItemsOnUi(copiedListedItems); associatedInstance.ContentPage.FocusSelectedItems(); } } } progress?.Report(100.0f); var pathWithType = copiedItem.FromStorageItem(destination, source.ItemType); return(new StorageHistory(FileOperationType.Copy, source, pathWithType)); }
public async Task <IStorageHistory> RestoreFromTrashAsync(IStorageItemWithPath source, string destination, IProgress <float> progress, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken) { FilesystemResult fsResult = FileSystemStatusCode.InProgress; errorCode?.Report(fsResult); fsResult = (FilesystemResult)await Task.Run(() => NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination)); if (!fsResult) { if (source.ItemType == FilesystemItemType.Directory) { FilesystemResult <StorageFolder> sourceFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(source.Path); FilesystemResult <StorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); fsResult = sourceFolder.ErrorCode | destinationFolder.ErrorCode; errorCode?.Report(fsResult); if (fsResult) { fsResult = await FilesystemTasks.Wrap(() => MoveDirectoryAsync(sourceFolder.Result, destinationFolder.Result, Path.GetFileName(destination), CreationCollisionOption.FailIfExists, true)); // TODO: we could use here FilesystemHelpers with registerHistory false? } errorCode?.Report(fsResult); } else { FilesystemResult <StorageFile> sourceFile = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(source.Path); FilesystemResult <StorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); fsResult = sourceFile.ErrorCode | destinationFolder.ErrorCode; errorCode?.Report(fsResult); if (fsResult) { fsResult = await FilesystemTasks.Wrap(() => sourceFile.Result.MoveAsync(destinationFolder.Result, Path.GetFileName(destination), NameCollisionOption.GenerateUniqueName).AsTask()); } errorCode?.Report(fsResult); } if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly) { fsResult = await PerformAdminOperation(new ValueSet() { { "Arguments", "FileOperation" }, { "fileop", "MoveItem" }, { "filepath", source.Path }, { "destpath", destination }, { "overwrite", false } }); } } if (fsResult) { // Recycle bin also stores a file starting with $I for each item string iFilePath = Path.Combine(Path.GetDirectoryName(source.Path), Path.GetFileName(source.Path).Replace("$R", "$I")); await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(iFilePath) .OnSuccess(iFile => iFile.DeleteAsync().AsTask()); } errorCode?.Report(fsResult); if (fsResult != FileSystemStatusCode.Success) { if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.Unauthorized)) { await DialogDisplayHelper.ShowDialogAsync("AccessDeniedDeleteDialog/Title".GetLocalized(), "AccessDeniedDeleteDialog/Text".GetLocalized()); } else if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.Unauthorized)) { await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized()); } else if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.AlreadyExists)) { await DialogDisplayHelper.ShowDialogAsync("ItemAlreadyExistsDialogTitle".GetLocalized(), "ItemAlreadyExistsDialogContent".GetLocalized()); } } return(new StorageHistory(FileOperationType.Restore, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType))); }
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 { var fsResult = await PerformAdminOperation(new ValueSet() { { "Arguments", "FileOperation" }, { "fileop", "RenameItem" }, { "filepath", source.Path }, { "newName", newName }, { "overwrite", collision == NameCollisionOption.ReplaceExisting } }); if (fsResult) { errorCode?.Report(FileSystemStatusCode.Success); return(new StorageHistory(FileOperationType.Rename, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType))); } } } 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 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)); }
private async Task PasteItemAsync(DataPackageView packageView, string destinationPath, DataPackageOperation acceptedOperation, IShellPage AppInstance, IProgress <uint> progress) { if (!packageView.Contains(StandardDataFormats.StorageItems)) { // Happens if you copy some text and then you Ctrl+V in FilesUWP // Should this be done in ModernShellPage? return; } IReadOnlyList <IStorageItem> itemsToPaste = await packageView.GetStorageItemsAsync(); if (AppInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath)) { // Do not paste files and folders inside the recycle bin await DialogDisplayHelper.ShowDialogAsync("ErrorDialogThisActionCannotBeDone".GetLocalized(), "ErrorDialogUnsupportedOperation".GetLocalized()); return; } List <IStorageItem> pastedSourceItems = new List <IStorageItem>(); HashSet <IStorageItem> pastedItems = new HashSet <IStorageItem>(); var totalItemsSize = CalculateTotalItemsSize(itemsToPaste); bool isItemSizeUnreported = totalItemsSize <= 0; foreach (IStorageItem item in itemsToPaste) { if (item.IsOfType(StorageItemTypes.Folder)) { if (!string.IsNullOrEmpty(item.Path) && destinationPath.IsSubPathOf(item.Path)) { ImpossibleActionResponseTypes responseType = ImpossibleActionResponseTypes.Abort; /// Currently following implementation throws exception until it is resolved keep it disabled /*Binding themeBind = new Binding(); * themeBind.Source = ThemeHelper.RootTheme; * * ContentDialog dialog = new ContentDialog() * { * Title = ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"), * Content = ResourceController.GetTranslation("ErrorDialogTheDestinationFolder") + " (" + destinationPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last() + ") " + ResourceController.GetTranslation("ErrorDialogIsASubfolder") + " (" + item.Name + ")", * PrimaryButtonText = ResourceController.GetTranslation("ErrorDialogSkip"), * CloseButtonText = ResourceController.GetTranslation("ErrorDialogCancel"), * PrimaryButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Skip; }), * CloseButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Abort; }), * }; * BindingOperations.SetBinding(dialog, FrameworkElement.RequestedThemeProperty, themeBind); * * await dialog.ShowAsync();*/ if (responseType == ImpossibleActionResponseTypes.Skip) { continue; } else if (responseType == ImpossibleActionResponseTypes.Abort) { return; } } else { if (!isItemSizeUnreported) { var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems)); uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize); progress.Report(progressValue); } await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(destinationPath) .OnSuccess(t => CloneDirectoryAsync((StorageFolder)item, t, item.Name)) .OnSuccess(t => { if (AppInstance.FilesystemViewModel.CheckFolderForHiddenAttribute(item.Path)) { // The source folder was hidden, apply hidden attribute to destination NativeFileOperationsHelper.SetFileAttribute(t.Path, FileAttributes.Hidden); } pastedSourceItems.Add(item); pastedItems.Add(t); }); } } else if (item.IsOfType(StorageItemTypes.File)) { if (!isItemSizeUnreported) { var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems)); uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize); progress.Report(progressValue); } var res = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(destinationPath); if (res) { StorageFile clipboardFile = (StorageFile)item; var pasted = await FilesystemTasks.Wrap(() => clipboardFile.CopyAsync(res.Result, item.Name, NameCollisionOption.GenerateUniqueName).AsTask()); if (pasted) { pastedSourceItems.Add(item); pastedItems.Add(pasted.Result); } else if (pasted.ErrorCode == FilesystemErrorCode.ERROR_UNAUTHORIZED) { // Try again with CopyFileFromApp if (NativeFileOperationsHelper.CopyFileFromApp(item.Path, Path.Combine(destinationPath, item.Name), true)) { pastedSourceItems.Add(item); } else { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } else if (pasted.ErrorCode == FilesystemErrorCode.ERROR_NOTFOUND) { // File was moved/deleted in the meantime continue; } } } } if (!isItemSizeUnreported) { var finalPastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems)); uint finalProgressValue = (uint)(finalPastedItemSize * 100 / totalItemsSize); progress.Report(finalProgressValue); } else { progress.Report(100); } if (acceptedOperation == DataPackageOperation.Move) { foreach (IStorageItem item in pastedSourceItems) { var deleted = (FilesystemResult)false; if (string.IsNullOrEmpty(item.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 continue; } if (item.IsOfType(StorageItemTypes.File)) { // If we reached this we are not in an MTP device, using StorageFile.* is ok here deleted = await AppInstance.FilesystemViewModel.GetFileFromPathAsync(item.Path) .OnSuccess(t => t.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask()); } else if (item.IsOfType(StorageItemTypes.Folder)) { // If we reached this we are not in an MTP device, using StorageFolder.* is ok here deleted = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(item.Path) .OnSuccess(t => t.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask()); } if (deleted == FilesystemErrorCode.ERROR_UNAUTHORIZED) { // Try again with fulltrust process if (AppInstance.FilesystemViewModel.Connection != null) { var response = await AppInstance.FilesystemViewModel.Connection.SendMessageAsync(new ValueSet() { { "Arguments", "FileOperation" }, { "fileop", "DeleteItem" }, { "filepath", item.Path }, { "permanently", true } }); deleted = (FilesystemResult)(response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success); } } else if (deleted == FilesystemErrorCode.ERROR_NOTFOUND) { // File or Folder was moved/deleted in the meantime continue; } } } if (destinationPath == AppInstance.FilesystemViewModel.WorkingDirectory) { List <string> pastedItemPaths = pastedItems.Select(item => item.Path).ToList(); List <ListedItem> copiedItems = AppInstance.FilesystemViewModel.FilesAndFolders.Where(listedItem => pastedItemPaths.Contains(listedItem.ItemPath)).ToList(); if (copiedItems.Any()) { AppInstance.ContentPage.SetSelectedItemsOnUi(copiedItems); AppInstance.ContentPage.FocusSelectedItems(); } } packageView.ReportOperationCompleted(acceptedOperation); }
private static async Task PasteItem(DataPackageView packageView, string destinationPath, DataPackageOperation acceptedOperation, IShellPage AppInstance, IProgress <uint> progress) { IReadOnlyList <IStorageItem> itemsToPaste = await packageView.GetStorageItemsAsync(); if (!packageView.Contains(StandardDataFormats.StorageItems)) { // Happens if you copy some text and then you Ctrl+V in FilesUWP // Should this be done in ModernShellPage? return; } if (AppInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath)) { // Do not paste files and folders inside the recycle bin await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"), ResourceController.GetTranslation("ErrorDialogUnsupportedOperation")); return; } List <IStorageItem> pastedSourceItems = new List <IStorageItem>(); HashSet <IStorageItem> pastedItems = new HashSet <IStorageItem>(); var totalItemsSize = CalculateTotalItemsSize(itemsToPaste); bool isItemSizeUnreported = totalItemsSize <= 0; foreach (IStorageItem item in itemsToPaste) { if (item.IsOfType(StorageItemTypes.Folder)) { if (!string.IsNullOrEmpty(item.Path) && destinationPath.IsSubPathOf(item.Path)) { ImpossibleActionResponseTypes responseType = ImpossibleActionResponseTypes.Abort; /// Currently following implementation throws exception until it is resolved keep it disabled /*Binding themeBind = new Binding(); * themeBind.Source = ThemeHelper.RootTheme; * * ContentDialog dialog = new ContentDialog() * { * Title = ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"), * Content = ResourceController.GetTranslation("ErrorDialogTheDestinationFolder") + " (" + destinationPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last() + ") " + ResourceController.GetTranslation("ErrorDialogIsASubfolder") + " (" + item.Name + ")", * PrimaryButtonText = ResourceController.GetTranslation("ErrorDialogSkip"), * CloseButtonText = ResourceController.GetTranslation("ErrorDialogCancel"), * PrimaryButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Skip; }), * CloseButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Abort; }), * }; * BindingOperations.SetBinding(dialog, FrameworkElement.RequestedThemeProperty, themeBind); * * await dialog.ShowAsync();*/ if (responseType == ImpossibleActionResponseTypes.Skip) { continue; } else if (responseType == ImpossibleActionResponseTypes.Abort) { return; } } else { if (!isItemSizeUnreported) { var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems)); uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize); progress.Report(progressValue); } try { ClonedDirectoryOutput pastedOutput = await CloneDirectoryAsync( (StorageFolder)item, await ItemViewModel.GetFolderFromPathAsync(destinationPath), item.Name); pastedSourceItems.Add(item); pastedItems.Add(pastedOutput.FolderOutput); } catch (FileNotFoundException) { // Folder was moved/deleted in the meantime continue; } } } else if (item.IsOfType(StorageItemTypes.File)) { if (!isItemSizeUnreported) { var pastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems)); uint progressValue = (uint)(pastedItemSize * 100 / totalItemsSize); progress.Report(progressValue); } try { StorageFile clipboardFile = (StorageFile)item; StorageFile pastedFile = await clipboardFile.CopyAsync( await ItemViewModel.GetFolderFromPathAsync(destinationPath), item.Name, NameCollisionOption.GenerateUniqueName); pastedSourceItems.Add(item); pastedItems.Add(pastedFile); } catch (UnauthorizedAccessException) { // Try again with CopyFileFromApp if (NativeDirectoryChangesHelper.CopyFileFromApp(item.Path, Path.Combine(destinationPath, item.Name), true)) { pastedSourceItems.Add(item); } else { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } catch (FileNotFoundException) { // File was moved/deleted in the meantime continue; } } } if (!isItemSizeUnreported) { var finalPastedItemSize = await Task.Run(() => CalculateTotalItemsSize(pastedSourceItems)); uint finalProgressValue = (uint)(finalPastedItemSize * 100 / totalItemsSize); progress.Report(finalProgressValue); } else { progress.Report(100); } if (acceptedOperation == DataPackageOperation.Move) { foreach (IStorageItem item in pastedSourceItems) { try { if (string.IsNullOrEmpty(item.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 continue; } if (item.IsOfType(StorageItemTypes.File)) { // If we reached this we are not in an MTP device, using StorageFile.* is ok here StorageFile file = await StorageFile.GetFileFromPathAsync(item.Path); await file.DeleteAsync(StorageDeleteOption.PermanentDelete); } else if (item.IsOfType(StorageItemTypes.Folder)) { // If we reached this we are not in an MTP device, using StorageFolder.* is ok here StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(item.Path); await folder.DeleteAsync(StorageDeleteOption.PermanentDelete); } } catch (UnauthorizedAccessException) { // Try again with DeleteFileFromApp if (!NativeDirectoryChangesHelper.DeleteFileFromApp(item.Path)) { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } catch (FileNotFoundException) { // File or Folder was moved/deleted in the meantime continue; } ListedItem listedItem = AppInstance.FilesystemViewModel.FilesAndFolders.FirstOrDefault(listedItem => listedItem.ItemPath.Equals(item.Path, StringComparison.OrdinalIgnoreCase)); } } if (destinationPath == AppInstance.FilesystemViewModel.WorkingDirectory) { List <string> pastedItemPaths = pastedItems.Select(item => item.Path).ToList(); List <ListedItem> copiedItems = AppInstance.FilesystemViewModel.FilesAndFolders.Where(listedItem => pastedItemPaths.Contains(listedItem.ItemPath)).ToList(); if (copiedItems.Any()) { AppInstance.ContentPage.SetSelectedItemsOnUi(copiedItems); AppInstance.ContentPage.FocusSelectedItems(); } } packageView.ReportOperationCompleted(acceptedOperation); }
private async Task <FilesystemResult> DeleteItemAsync(StorageDeleteOption deleteOption, IShellPage AppInstance, IProgress <uint> progress) { var deleted = (FilesystemResult)false; var deleteFromRecycleBin = AppInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath); List <ListedItem> selectedItems = new List <ListedItem>(); foreach (ListedItem selectedItem in AppInstance.ContentPage.SelectedItems) { selectedItems.Add(selectedItem); } if (App.AppSettings.ShowConfirmDeleteDialog == true) //check if the setting to show a confirmation dialog is on { var dialog = new ConfirmDeleteDialog(deleteFromRecycleBin, deleteOption, AppInstance.ContentPage.SelectedItemsPropertiesViewModel); await dialog.ShowAsync(); if (dialog.Result != MyResult.Delete) //delete selected item(s) if the result is yes { return((FilesystemResult)true); //return if the result isn't delete } deleteOption = dialog.PermanentlyDelete; } int itemsDeleted = 0; foreach (ListedItem storItem in selectedItems) { uint progressValue = (uint)(itemsDeleted * 100.0 / selectedItems.Count); if (selectedItems.Count > 3) { progress.Report(progressValue); } if (storItem.PrimaryItemAttribute == StorageItemTypes.File) { deleted = await AppInstance.FilesystemViewModel.GetFileFromPathAsync(storItem.ItemPath) .OnSuccess(t => t.DeleteAsync(deleteOption).AsTask()); } else { deleted = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(storItem.ItemPath) .OnSuccess(t => t.DeleteAsync(deleteOption).AsTask()); } if (deleted.ErrorCode == FilesystemErrorCode.ERROR_UNAUTHORIZED) { // Try again with fulltrust process if (AppInstance.FilesystemViewModel.Connection != null) { var response = await AppInstance.FilesystemViewModel.Connection.SendMessageAsync(new ValueSet() { { "Arguments", "FileOperation" }, { "fileop", "DeleteItem" }, { "filepath", storItem.ItemPath }, { "permanently", deleteOption == StorageDeleteOption.PermanentDelete } }); deleted = (FilesystemResult)(response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success); } } else if (deleted.ErrorCode == FilesystemErrorCode.ERROR_INUSE) { // TODO: retry or show dialog await DialogDisplayHelper.ShowDialogAsync("FileInUseDeleteDialog/Title".GetLocalized(), "FileInUseDeleteDialog/Text".GetLocalized()); } if (deleteFromRecycleBin) { // Recycle bin also stores a file starting with $I for each item var iFilePath = Path.Combine(Path.GetDirectoryName(storItem.ItemPath), Path.GetFileName(storItem.ItemPath).Replace("$R", "$I")); await AppInstance.FilesystemViewModel.GetFileFromPathAsync(iFilePath) .OnSuccess(t => t.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask()); } if (deleted) { await AppInstance.FilesystemViewModel.RemoveFileOrFolderAsync(storItem); itemsDeleted++; } else { // Stop at first error return(deleted); } } return((FilesystemResult)true); }
private async Task ImportSettings() { FileOpenPicker filePicker = new FileOpenPicker(); filePicker.FileTypeFilter.Add(".zip"); StorageFile file = await filePicker.PickSingleFileAsync(); if (file != null) { try { var zipFolder = await ZipStorageFolder.FromStorageFileAsync(file); if (zipFolder == null) { return; } var localFolderPath = ApplicationData.Current.LocalFolder.Path; var settingsFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(localFolderPath, Constants.LocalSettings.SettingsFolderName)); // Import user settings var userSettingsFile = await zipFolder.GetFileAsync(Constants.LocalSettings.UserSettingsFileName); string importSettings = await userSettingsFile.ReadTextAsync(); UserSettingsService.ImportSettings(importSettings); // Import bundles var bundles = await zipFolder.GetFileAsync(Constants.LocalSettings.BundlesSettingsFileName); string importBundles = await bundles.ReadTextAsync(); BundlesSettingsService.ImportSettings(importBundles); // Import pinned items var pinnedItems = await zipFolder.GetFileAsync(App.SidebarPinnedController.JsonFileName); await pinnedItems.CopyAsync(settingsFolder, pinnedItems.Name, NameCollisionOption.ReplaceExisting); await App.SidebarPinnedController.ReloadAsync(); // Import terminals config var terminals = await zipFolder.GetFileAsync(App.TerminalController.JsonFileName); await terminals.CopyAsync(settingsFolder, terminals.Name, NameCollisionOption.ReplaceExisting); // Import file tags list and DB var fileTagsList = await zipFolder.GetFileAsync(Constants.LocalSettings.FileTagSettingsFileName); string importTags = await fileTagsList.ReadTextAsync(); FileTagsSettingsService.ImportSettings(importTags); var fileTagsDB = await zipFolder.GetFileAsync(Path.GetFileName(FileTagsHelper.FileTagsDbPath)); string importTagsDB = await fileTagsDB.ReadTextAsync(); FileTagsHelper.DbInstance.Import(importTagsDB); // Import layout preferences and DB var layoutPrefsDB = await zipFolder.GetFileAsync(Path.GetFileName(FolderSettingsViewModel.LayoutSettingsDbPath)); string importPrefsDB = await layoutPrefsDB.ReadTextAsync(); FolderSettingsViewModel.DbInstance.Import(importPrefsDB); } catch (Exception ex) { App.Logger.Warn(ex, "Error importing settings"); UIHelpers.CloseAllDialogs(); await DialogDisplayHelper.ShowDialogAsync("SettingsImportErrorTitle".GetLocalized(), "SettingsImportErrorDescription".GetLocalized()); } } }
public async Task <IStorageHistory> CopyAsync(PathWithType source, string destination, IProgress <float> progress, IProgress <FilesystemErrorCode> errorCode, CancellationToken cancellationToken) { if (associatedInstance.FilesystemViewModel.WorkingDirectory.StartsWith(App.AppSettings.RecycleBinPath)) { errorCode?.Report(FilesystemErrorCode.ERROR_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.Path.ToStorageItem()); bool reportProgress = false; // TODO: The default value is false 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 { ImpossibleActionResponseTypes responseType = ImpossibleActionResponseTypes.Abort; /*if (ShowDialog) * { * /// Currently following implementation throws exception until it is resolved keep it disabled * Binding themeBind = new Binding(); * themeBind.Source = ThemeHelper.RootTheme; * ContentDialog dialog = new ContentDialog() * { * Title = ResourceController.GetTranslation("ErrorDialogThisActionCannotBeDone"), * Content = ResourceController.GetTranslation("ErrorDialogTheDestinationFolder") + " (" + destinationPath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last() + ") " + ResourceController.GetTranslation("ErrorDialogIsASubfolder") + " (" + item.Name + ")", * PrimaryButtonText = ResourceController.GetTranslation("ErrorDialogSkip"), * CloseButtonText = ResourceController.GetTranslation("ErrorDialogCancel"), * PrimaryButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Skip; }), * CloseButtonCommand = new RelayCommand(() => { responseType = ImpossibleActionResponseTypes.Abort; }), * }; * BindingOperations.SetBinding(dialog, FrameworkElement.RequestedThemeProperty, themeBind); * await dialog.ShowAsync(); * }*/ if (responseType == ImpossibleActionResponseTypes.Skip) { progress?.Report(100.0f); errorCode?.Report(FilesystemErrorCode.ERROR_SUCCESS | FilesystemErrorCode.ERROR_INPROGRESS); } else if (responseType == ImpossibleActionResponseTypes.Abort) { progress?.Report(100.0f); errorCode?.Report(FilesystemErrorCode.ERROR_INPROGRESS | FilesystemErrorCode.ERROR_GENERIC); } return(null); } else { if (reportProgress) { progress?.Report((float)(itemSize * 100.0f / itemSize)); } FilesystemResult <StorageFolder> fsSourceFolderResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(source.Path)); FilesystemResult <StorageFolder> fsDestinationFolderResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); if (fsSourceFolderResult && fsDestinationFolderResult) { FilesystemResult fsCopyResult = await FilesystemTasks.Wrap(async() => { return(await FilesystemHelpers.CloneDirectoryAsync(fsSourceFolderResult.Result, fsDestinationFolderResult.Result, Path.GetFileName(source.Path))); }) .OnSuccess(t => { if (associatedInstance.FilesystemViewModel.CheckFolderForHiddenAttribute(source.Path)) { // The source folder was hidden, apply hidden attribute to destination NativeFileOperationsHelper.SetFileAttribute(t.Path, FileAttributes.Hidden); } copiedItem = t; }); } } } else if (source.ItemType == FilesystemItemType.File) { if (reportProgress) { progress?.Report((float)(itemSize * 100.0f / itemSize)); } FilesystemResult <StorageFolder> fsResult = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); if (fsResult) { StorageFile file = (StorageFile)await source.Path.ToStorageItem(); FilesystemResult <StorageFile> fsResultCopy = new FilesystemResult <StorageFile>(null, FilesystemErrorCode.ERROR_GENERIC); if (file != null) { fsResultCopy = await FilesystemTasks.Wrap(() => { return(file.CopyAsync(fsResult.Result, Path.GetFileName(source.Path), NameCollisionOption.GenerateUniqueName).AsTask()); }); } if (fsResultCopy) { copiedItem = fsResultCopy.Result; } else if (fsResultCopy.ErrorCode == FilesystemErrorCode.ERROR_UNAUTHORIZED || fsResultCopy.ErrorCode == FilesystemErrorCode.ERROR_GENERIC) { // Try again with CopyFileFromApp if (NativeFileOperationsHelper.CopyFileFromApp(source.Path, destination, true)) { copiedItem = await source.Path.ToStorageItem(); // Dangerous - the provided item may be different than output result! } else { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } else { errorCode?.Report(fsResultCopy.ErrorCode); } } } if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory) { if (copiedItem != null) { List <ListedItem> copiedListedItems = associatedInstance.FilesystemViewModel.FilesAndFolders .Where(listedItem => copiedItem.Path.Contains(listedItem.ItemPath)).ToList(); if (copiedListedItems.Count > 0) { associatedInstance.ContentPage.AddSelectedItemsOnUi(copiedListedItems); associatedInstance.ContentPage.FocusSelectedItems(); } } } progress?.Report(100.0f); var pathWithType = new PathWithType( copiedItem != null ? (!string.IsNullOrWhiteSpace(copiedItem.Path) ? copiedItem.Path : destination) : destination, source.ItemType); return(new StorageHistory(FileOperationType.Copy, source, pathWithType)); }
public async Task <IStorageHistory> RenameAsync(IStorageItemWithPath source, string newName, NameCollisionOption collision, IProgress <FilesystemErrorCode> errorCode, CancellationToken cancellationToken) { if (Path.GetFileName(source.Path) == newName && collision == NameCollisionOption.FailIfExists) { errorCode?.Report(FilesystemErrorCode.ERROR_ALREADYEXIST); return(null); } if (!string.IsNullOrWhiteSpace(newName) && !FilesystemHelpers.ContainsRestrictedCharacters(newName) && !FilesystemHelpers.ContainsRestrictedFileName(newName)) { var renamed = await source.ToStorageItemResult(associatedInstance) .OnSuccess(async(t) => { await t.RenameAsync(newName, collision); return(t); }); if (renamed) { errorCode?.Report(FilesystemErrorCode.ERROR_SUCCESS); return(new StorageHistory(FileOperationType.Rename, source, renamed.Result.FromStorageItem())); } else if (renamed == FilesystemErrorCode.ERROR_UNAUTHORIZED) { // Try again with MoveFileFromApp var destination = Path.Combine(Path.GetDirectoryName(source.Path), newName); if (NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination)) { errorCode?.Report(FilesystemErrorCode.ERROR_SUCCESS); return(new StorageHistory(FileOperationType.Rename, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType))); } else { Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); } } else if (renamed == FilesystemErrorCode.ERROR_NOTAFILE || renamed == FilesystemErrorCode.ERROR_NOTAFOLDER) { await DialogDisplayHelper.ShowDialogAsync("RenameError/NameInvalid/Title".GetLocalized(), "RenameError/NameInvalid/Text".GetLocalized()); } else if (renamed == FilesystemErrorCode.ERROR_NAMETOOLONG) { await DialogDisplayHelper.ShowDialogAsync("RenameError/TooLong/Title".GetLocalized(), "RenameError/TooLong/Text".GetLocalized()); } else if (renamed == FilesystemErrorCode.ERROR_INUSE) { // TODO: proper dialog, retry await DialogDisplayHelper.ShowDialogAsync("FileInUseDeleteDialog/Title".GetLocalized(), ""); } else if (renamed == FilesystemErrorCode.ERROR_NOTFOUND) { await DialogDisplayHelper.ShowDialogAsync("RenameError/ItemDeleted/Title".GetLocalized(), "RenameError/ItemDeleted/Text".GetLocalized()); } else if (renamed == FilesystemErrorCode.ERROR_ALREADYEXIST) { var ItemAlreadyExistsDialog = new ContentDialog() { Title = "ItemAlreadyExistsDialogTitle".GetLocalized(), Content = "ItemAlreadyExistsDialogContent".GetLocalized(), PrimaryButtonText = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(), SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(), CloseButtonText = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized() }; 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 async Task <IStorageHistory> CopyAsync(IStorageItemWithPath source, string destination, 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, CreationCollisionOption.FailIfExists)); if (fsCopyResult == FileSystemStatusCode.AlreadyExists) { var ItemAlreadyExistsDialog = new ContentDialog() { Title = "ItemAlreadyExistsDialogTitle".GetLocalized(), Content = "ItemAlreadyExistsDialogContent".GetLocalized(), PrimaryButtonText = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(), SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(), CloseButtonText = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized() }; if (Interacts.Interaction.IsAnyContentDialogOpen()) { // Only a single ContentDialog can be open at any time. return(null); } ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, CreationCollisionOption.GenerateUniqueName)); } else if (result == ContentDialogResult.Secondary) { fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync((StorageFolder)fsSourceFolder, (StorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, CreationCollisionOption.ReplaceExisting)); return(null); // Cannot undo overwrite operation } else { 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), NameCollisionOption.FailIfExists).AsTask()); if (fsResultCopy == FileSystemStatusCode.AlreadyExists) { var ItemAlreadyExistsDialog = new ContentDialog() { Title = "ItemAlreadyExistsDialogTitle".GetLocalized(), Content = "ItemAlreadyExistsDialogContent".GetLocalized(), PrimaryButtonText = "ItemAlreadyExistsDialogPrimaryButtonText".GetLocalized(), SecondaryButtonText = "ItemAlreadyExistsDialogSecondaryButtonText".GetLocalized(), CloseButtonText = "ItemAlreadyExistsDialogCloseButtonText".GetLocalized() }; if (Interacts.Interaction.IsAnyContentDialogOpen()) { // Only a single ContentDialog can be open at any time. return(null); } ContentDialogResult result = await ItemAlreadyExistsDialog.ShowAsync(); if (result == ContentDialogResult.Primary) { fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.GenerateUniqueName).AsTask()); } else if (result == ContentDialogResult.Secondary) { fsResultCopy = await FilesystemTasks.Wrap(() => file.CopyAsync(destinationResult.Result, Path.GetFileName(file.Name), NameCollisionOption.ReplaceExisting).AsTask()); return(null); // Cannot undo overwrite operation } else { return(null); } } if (fsResultCopy) { copiedItem = fsResultCopy.Result; } fsResult = fsResultCopy; } } errorCode?.Report(fsResult.ErrorCode); if (!fsResult) { return(null); } } if (Path.GetDirectoryName(destination) == associatedInstance.FilesystemViewModel.WorkingDirectory) { _ = Windows.ApplicationModel.Core.CoreApplication.MainView.ExecuteOnUIThreadAsync(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) { associatedInstance.ContentPage.AddSelectedItemsOnUi(copiedListedItems); associatedInstance.ContentPage.FocusSelectedItems(); } }, Windows.UI.Core.CoreDispatcherPriority.Low); } progress?.Report(100.0f); var pathWithType = copiedItem.FromStorageItem(destination, source.ItemType); return(new StorageHistory(FileOperationType.Copy, source, pathWithType)); }
private async void OpenSelectedItems(bool displayApplicationPicker) { try { int selectedItemCount; Type sourcePageType = App.CurrentInstance.CurrentPageType; selectedItemCount = CurrentInstance.ContentPage.SelectedItems.Count; // Access MRU List var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; if (selectedItemCount == 1) { var clickedOnItem = CurrentInstance.ContentPage.SelectedItem; var clickedOnItemPath = clickedOnItem.ItemPath; if (clickedOnItem.PrimaryItemAttribute == StorageItemTypes.Folder) { // Add location to MRU List mostRecentlyUsed.Add(await StorageFolder.GetFolderFromPathAsync(clickedOnItemPath)); CurrentInstance.ViewModel.WorkingDirectory = clickedOnItemPath; CurrentInstance.NavigationToolbar.PathControlDisplayText = clickedOnItemPath; CurrentInstance.ContentPage.AssociatedViewModel.EmptyTextState.IsVisible = Visibility.Collapsed; CurrentInstance.ContentFrame.Navigate(sourcePageType, clickedOnItemPath, new SuppressNavigationTransitionInfo()); } else { // Add location to MRU List mostRecentlyUsed.Add(await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath)); if (displayApplicationPicker) { StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath); var options = new LauncherOptions { DisplayApplicationPicker = true }; await Launcher.LaunchFileAsync(file, options); } else { await InvokeWin32Component(clickedOnItem.ItemPath); } } } else if (selectedItemCount > 1) { foreach (ListedItem clickedOnItem in CurrentInstance.ContentPage.SelectedItems) { if (clickedOnItem.PrimaryItemAttribute == StorageItemTypes.Folder) { instanceTabsView.AddNewTab(typeof(ModernShellPage), clickedOnItem.ItemPath); } else { // Add location to MRU List mostRecentlyUsed.Add(await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath)); if (displayApplicationPicker) { StorageFile file = await StorageFile.GetFileFromPathAsync(clickedOnItem.ItemPath); var options = new LauncherOptions { DisplayApplicationPicker = true }; await Launcher.LaunchFileAsync(file, options); } else { await InvokeWin32Component(clickedOnItem.ItemPath); } } } } } catch (FileNotFoundException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("FileNotFoundDialog.Title"), ResourceController.GetTranslation("FileNotFoundDialog.Text")); NavigationActions.Refresh_Click(null, null); } }
public async void DeleteItem_Click(object sender, RoutedEventArgs e) { if (App.AppSettings.ShowConfirmDeleteDialog == true) //check if the setting to show a confirmation dialog is on { var dialog = new ConfirmDeleteDialog(); await dialog.ShowAsync(); if (dialog.Result != MyResult.Delete) //delete selected item(s) if the result is yes { return; //return if the result isn't delete } } try { var CurrentInstance = App.CurrentInstance; List <ListedItem> selectedItems = new List <ListedItem>(); foreach (ListedItem selectedItem in CurrentInstance.ContentPage.SelectedItems) { selectedItems.Add(selectedItem); } int itemsDeleted = 0; if (selectedItems.Count > 3) { (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.DeleteItems, itemsDeleted, selectedItems.Count); } foreach (ListedItem storItem in selectedItems) { if (selectedItems.Count > 3) { (App.CurrentInstance as ModernShellPage).UpdateProgressFlyout(InteractionOperationType.DeleteItems, ++itemsDeleted, selectedItems.Count); } IStorageItem item; try { if (storItem.PrimaryItemAttribute == StorageItemTypes.File) { item = await StorageFile.GetFileFromPathAsync(storItem.ItemPath); } else { item = await StorageFolder.GetFolderFromPathAsync(storItem.ItemPath); } await item.DeleteAsync(App.InteractionViewModel.PermanentlyDelete); } catch (FileLoadException) { // try again if (storItem.PrimaryItemAttribute == StorageItemTypes.File) { item = await StorageFile.GetFileFromPathAsync(storItem.ItemPath); } else { item = await StorageFolder.GetFolderFromPathAsync(storItem.ItemPath); } await item.DeleteAsync(App.InteractionViewModel.PermanentlyDelete); } CurrentInstance.ViewModel.RemoveFileOrFolder(storItem); } App.CurrentInstance.NavigationToolbar.CanGoForward = false; } catch (UnauthorizedAccessException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("AccessDeniedDeleteDialog.Title"), ResourceController.GetTranslation("AccessDeniedDeleteDialog.Text")); } catch (FileNotFoundException) { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("FileNotFoundDialog.Title"), ResourceController.GetTranslation("FileNotFoundDialog.Text")); } App.InteractionViewModel.PermanentlyDelete = StorageDeleteOption.Default; //reset PermanentlyDelete flag }
public async Task <IStorageHistory> RestoreFromTrashAsync(IStorageItemWithPath source, string destination, IProgress <float> progress, IProgress <FilesystemErrorCode> errorCode, CancellationToken cancellationToken) { FilesystemResult fsResult = FilesystemErrorCode.ERROR_INPROGRESS; errorCode?.Report(fsResult); if (source.ItemType == FilesystemItemType.Directory) { FilesystemResult <StorageFolder> sourceFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(source.Path); FilesystemResult <StorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); fsResult = sourceFolder.ErrorCode | destinationFolder.ErrorCode; errorCode?.Report(fsResult); if (fsResult) { fsResult = await FilesystemTasks.Wrap(() => { return(MoveDirectoryAsync(sourceFolder.Result, destinationFolder.Result, Path.GetFileName(destination), CreationCollisionOption.FailIfExists)); }).OnSuccess(t => sourceFolder.Result.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask()); // TODO: we could use here FilesystemHelpers with registerHistory false? } errorCode?.Report(fsResult); } else { FilesystemResult <StorageFile> sourceFile = await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(source.Path); FilesystemResult <StorageFolder> destinationFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(Path.GetDirectoryName(destination)); fsResult = sourceFile.ErrorCode | destinationFolder.ErrorCode; errorCode?.Report(fsResult); if (fsResult) { fsResult = await FilesystemTasks.Wrap(() => { return(sourceFile.Result.MoveAsync(destinationFolder.Result, Path.GetFileName(destination), NameCollisionOption.GenerateUniqueName).AsTask()); }); } else if (fsResult == FilesystemErrorCode.ERROR_UNAUTHORIZED) { // Try again with MoveFileFromApp fsResult = (FilesystemResult)NativeFileOperationsHelper.MoveFileFromApp(source.Path, destination); } errorCode?.Report(fsResult); } if (fsResult) { // Recycle bin also stores a file starting with $I for each item string iFilePath = Path.Combine(Path.GetDirectoryName(source.Path), Path.GetFileName(source.Path).Replace("$R", "$I")); await associatedInstance.FilesystemViewModel.GetFileFromPathAsync(iFilePath) .OnSuccess(iFile => iFile.DeleteAsync().AsTask()); } errorCode?.Report(fsResult); if (fsResult != FilesystemErrorCode.ERROR_SUCCESS) { if (((FilesystemErrorCode)fsResult).HasFlag(FilesystemErrorCode.ERROR_UNAUTHORIZED)) { await DialogDisplayHelper.ShowDialogAsync("AccessDeniedDeleteDialog/Title".GetLocalized(), "AccessDeniedDeleteDialog/Text".GetLocalized()); } else if (((FilesystemErrorCode)fsResult).HasFlag(FilesystemErrorCode.ERROR_UNAUTHORIZED)) { await DialogDisplayHelper.ShowDialogAsync("FileNotFoundDialog/Title".GetLocalized(), "FileNotFoundDialog/Text".GetLocalized()); } else if (((FilesystemErrorCode)fsResult).HasFlag(FilesystemErrorCode.ERROR_ALREADYEXIST)) { await DialogDisplayHelper.ShowDialogAsync("ItemAlreadyExistsDialogTitle".GetLocalized(), "ItemAlreadyExistsDialogContent".GetLocalized()); } } return(new StorageHistory(FileOperationType.Restore, source, StorageItemHelpers.FromPathAndType(destination, source.ItemType))); }
public async void CheckPathInput(ItemViewModel instance, string currentInput, string currentSelectedPath) { if (currentSelectedPath == currentInput) { return; } if (currentInput != instance.WorkingDirectory || App.CurrentInstance.ContentFrame.CurrentSourcePageType == typeof(YourHome)) { //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.HomeItems.isEnabled = false; //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.ShareItems.isEnabled = false; if (currentInput.Equals("Home", StringComparison.OrdinalIgnoreCase) || currentInput.Equals(ResourceController.GetTranslation("NewTab"), StringComparison.OrdinalIgnoreCase)) { await App.CurrentInstance.FilesystemViewModel.SetWorkingDirectory(ResourceController.GetTranslation("NewTab")); App.CurrentInstance.ContentFrame.Navigate(typeof(YourHome), ResourceController.GetTranslation("NewTab"), new SuppressNavigationTransitionInfo()); } else { var workingDir = string.IsNullOrEmpty(App.CurrentInstance.FilesystemViewModel.WorkingDirectory) ? AppSettings.HomePath : App.CurrentInstance.FilesystemViewModel.WorkingDirectory; currentInput = StorageFileExtensions.GetPathWithoutEnvironmentVariable(currentInput); if (currentSelectedPath == currentInput) { return; } var item = await DrivesManager.GetRootFromPath(currentInput); try { var pathToNavigate = (await StorageFileExtensions.GetFolderWithPathFromPathAsync(currentInput, item)).Path; App.CurrentInstance.ContentFrame.Navigate(AppSettings.GetLayoutType(), pathToNavigate); // navigate to folder } catch (Exception) // Not a folder or inaccessible { try { var pathToInvoke = (await StorageFileExtensions.GetFileWithPathFromPathAsync(currentInput, item)).Path; await Interaction.InvokeWin32Component(pathToInvoke); } catch (Exception ex) // Not a file or not accessible { // Launch terminal application if possible foreach (var terminal in AppSettings.TerminalController.Model.Terminals) { if (terminal.Path.Equals(currentInput, StringComparison.OrdinalIgnoreCase) || terminal.Path.Equals(currentInput + ".exe", StringComparison.OrdinalIgnoreCase)) { if (App.Connection != null) { var value = new ValueSet { { "WorkingDirectory", workingDir }, { "Application", terminal.Path }, { "Arguments", string.Format(terminal.Arguments, Helpers.PathNormalization.NormalizePath(App.CurrentInstance.FilesystemViewModel.WorkingDirectory)) } }; await App.Connection.SendMessageAsync(value); } return; } } try { if (!await Launcher.LaunchUriAsync(new Uri(currentInput))) { throw new Exception(); } } catch { await DialogDisplayHelper.ShowDialog(ResourceController.GetTranslation("InvalidItemDialogTitle"), string.Format(ResourceController.GetTranslation("InvalidItemDialogContent"), ex.Message)); } } } } App.CurrentInstance.NavigationToolbar.PathControlDisplayText = App.CurrentInstance.FilesystemViewModel.WorkingDirectory; } }