public static async Task <bool> RenameFileItemAsync(ListedItem item, string newName, IShellPage associatedInstance) { newName = item.ItemNameRaw.Replace(item.ItemName, newName, StringComparison.Ordinal); if (item.ItemNameRaw == newName || string.IsNullOrEmpty(newName)) { return(true); } ReturnResult renamed = ReturnResult.InProgress; if (item.PrimaryItemAttribute == StorageItemTypes.Folder) { renamed = await associatedInstance.FilesystemHelpers.RenameAsync(StorageHelpers.FromPathAndType(item.ItemPath, FilesystemItemType.Directory), newName, NameCollisionOption.FailIfExists, true); } else { renamed = await associatedInstance.FilesystemHelpers.RenameAsync(StorageHelpers.FromPathAndType(item.ItemPath, FilesystemItemType.File), newName, NameCollisionOption.FailIfExists, true); } if (renamed == ReturnResult.Success) { associatedInstance.NavToolbarViewModel.CanGoForward = false; return(true); } return(false); }
/// <summary> /// Rotates the image at the specified file path. /// </summary> /// <param name="filePath">The file path to the image.</param> /// <param name="rotation">The rotation direction.</param> /// <remarks> /// https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder?view=winrt-22000 /// https://docs.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapencoder?view=winrt-22000 /// </remarks> public static async Task Rotate(string filePath, BitmapRotation rotation) { if (string.IsNullOrEmpty(filePath)) { return; } var file = await StorageHelpers.ToStorageItem <IStorageFile>(filePath); if (file == null) { return; } using IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); using var memStream = new InMemoryRandomAccessStream(); BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder); encoder.BitmapTransform.Rotation = rotation; await encoder.FlushAsync(); memStream.Seek(0); fileStream.Seek(0); fileStream.Size = 0; await RandomAccessStream.CopyAsync(memStream, fileStream); }
public static async Task <byte[]> LoadIconFromPathAsync(string filePath, uint thumbnailSize, ThumbnailMode thumbnailMode) { if (!filePath.EndsWith(".lnk", StringComparison.Ordinal) && !filePath.EndsWith(".url", StringComparison.Ordinal)) { var item = await StorageHelpers.ToStorageItem <IStorageItem>(filePath); if (item != null) { var iconData = await LoadIconFromStorageItemAsync(item, thumbnailSize, thumbnailMode); if (iconData != null) { return(iconData); } } } return(await LoadIconWithoutOverlayAsync(filePath, thumbnailSize)); }
public static async void SetAsBackground(WallpaperType type, string filePath, IShellPage associatedInstance) { if (UserProfilePersonalizationSettings.IsSupported()) { // Get the path of the selected file BaseStorageFile sourceFile = await StorageHelpers.ToStorageItem <BaseStorageFile>(filePath, associatedInstance); if (sourceFile == null) { return; } // Get the app's local folder to use as the destination folder. BaseStorageFolder localFolder = ApplicationData.Current.LocalFolder; // the file to the destination folder. // Generate unique name if the file already exists. // If the file you are trying to set as the wallpaper has the same name as the current wallpaper, // the system will ignore the request and no-op the operation BaseStorageFile file = await FilesystemTasks.Wrap(() => sourceFile.CopyAsync(localFolder, sourceFile.Name, NameCollisionOption.GenerateUniqueName).AsTask()); if (file == null) { return; } UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current; if (type == WallpaperType.Desktop) { // Set the desktop background await profileSettings.TrySetWallpaperImageAsync(await file.ToStorageFileAsync()); } else if (type == WallpaperType.LockScreen) { // Set the lockscreen background await profileSettings.TrySetLockScreenImageAsync(await file.ToStorageFileAsync()); } } }
public static async Task <IStorageItem> CreateFileFromDialogResultTypeForResult(AddItemType itemType, ShellNewEntry itemInfo, IShellPage associatedInstance) { string currentPath = null; if (associatedInstance.SlimContentPage != null) { currentPath = associatedInstance.FilesystemViewModel.WorkingDirectory; if (App.LibraryManager.TryGetLibrary(currentPath, out var library)) { if (!library.IsEmpty && library.Folders.Count == 1) // TODO: handle libraries with multiple folders { currentPath = library.Folders.First(); } } } // Show rename dialog DynamicDialog dialog = DynamicDialogFactory.GetFor_RenameDialog(); await dialog.ShowAsync(); if (dialog.DynamicResult != DynamicDialogResult.Primary) { return(null); } // Create file based on dialog result string userInput = dialog.ViewModel.AdditionalData as string; var folderRes = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(currentPath); var created = new FilesystemResult <(ReturnResult, IStorageItem)>((ReturnResult.Failed, null), FileSystemStatusCode.Generic); if (folderRes) { switch (itemType) { case AddItemType.Folder: userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewFolder".GetLocalized(); created = await FilesystemTasks.Wrap(async() => { return(await associatedInstance.FilesystemHelpers.CreateAsync( StorageHelpers.FromPathAndType(PathNormalization.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( StorageHelpers.FromPathAndType(PathNormalization.Combine(folderRes.Result.Path, userInput + itemInfo?.Extension), FilesystemItemType.File), true)); }); break; } } if (created == FileSystemStatusCode.Unauthorized) { await DialogDisplayHelper.ShowDialogAsync("AccessDenied".GetLocalized(), "AccessDeniedCreateDialog/Text".GetLocalized()); } return(created.Result.Item2); }
/// <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.NavToolbarViewModel.CanRefresh = false; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var ContentOwnedViewModelInstance = associatedInstance.FilesystemViewModel; ContentOwnedViewModelInstance?.RefreshItems(previousDir); }); } return(opened); }