public async override void GetSpecialProperties() { ViewModel.IsReadOnly = NativeFileOperationsHelper.HasFileAttribute(Library.ItemPath, System.IO.FileAttributes.ReadOnly); ViewModel.IsHidden = NativeFileOperationsHelper.HasFileAttribute(Library.ItemPath, System.IO.FileAttributes.Hidden); var fileIconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Library.ItemPath, 80); if (fileIconData != null) { ViewModel.IconData = fileIconData; ViewModel.LoadCustomIcon = false; ViewModel.LoadFileIcon = true; } BaseStorageFile libraryFile = await AppInstance.FilesystemViewModel.GetFileFromPathAsync(Library.ItemPath); if (libraryFile != null) { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; string returnformat = Enum.Parse <TimeStyle>(localSettings.Values[Constants.LocalSettings.DateTimeFormat].ToString()) == TimeStyle.Application ? "D" : "g"; ViewModel.ItemCreatedTimestamp = libraryFile.DateCreated.GetFriendlyDateFromFormat(returnformat); if (libraryFile.Properties != null) { GetOtherProperties(libraryFile.Properties); } } var storageFolders = new List <BaseStorageFolder>(); if (Library.Folders != null) { try { foreach (var path in Library.Folders) { BaseStorageFolder folder = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(path); if (!string.IsNullOrEmpty(folder.Path)) { storageFolders.Add(folder); } } } catch (Exception ex) { App.Logger.Warn(ex, ex.Message); } } if (storageFolders.Count > 0) { ViewModel.ContainsFilesOrFolders = true; ViewModel.LocationsCount = storageFolders.Count; GetLibrarySize(storageFolders, TokenSource.Token); } else { ViewModel.FilesAndFoldersCountString = "LibraryNoLocations/Text".GetLocalized(); } }
public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { return(AsyncInfo.Run(async(cancellationToken) => { using var ftpClient = new FtpClient(); ftpClient.Host = FtpHelpers.GetFtpHost(Path); ftpClient.Port = FtpHelpers.GetFtpPort(Path); ftpClient.Credentials = FtpManager.Credentials.Get(ftpClient.Host, FtpManager.Anonymous); if (!await ftpClient.EnsureConnectedAsync()) { return null; } BaseStorageFolder destFolder = destinationFolder.AsBaseStorageFolder(); BaseStorageFile file = await destFolder.CreateFileAsync(desiredNewName, option.Convert()); var stream = await file.OpenStreamForWriteAsync(); if (await ftpClient.DownloadAsync(stream, FtpPath, token: cancellationToken)) { return file; } return null; })); }
private static async Task <ListedItem> AddFolderAsync(BaseStorageFolder folder, StorageFolderWithPath currentStorageFolder, string dateReturnFormat, CancellationToken cancellationToken) { var basicProperties = await folder.GetBasicPropertiesAsync(); if (!cancellationToken.IsCancellationRequested) { return(new ListedItem(folder.FolderRelativeId, dateReturnFormat) { PrimaryItemAttribute = StorageItemTypes.Folder, ItemName = folder.DisplayName, ItemDateModifiedReal = basicProperties.DateModified, ItemDateCreatedReal = folder.DateCreated, ItemType = folder.DisplayType, IsHiddenItem = false, Opacity = 1, LoadFolderGlyph = true, FileImage = null, LoadFileIcon = false, ItemPath = string.IsNullOrEmpty(folder.Path) ? PathNormalization.Combine(currentStorageFolder.Path, folder.Name) : folder.Path, LoadUnknownTypeGlyph = false, FileSize = null, FileSizeBytes = 0 }); } return(null); }
private async void GetFolderSize(BaseStorageFolder storageFolder, CancellationToken token) { if (string.IsNullOrEmpty(storageFolder.Path)) { // In MTP devices calculating folder size would be too slow // Also should use StorageFolder methods instead of FindFirstFileExFromApp return; } ViewModel.ItemSizeVisibility = Visibility.Visible; ViewModel.ItemSizeProgressVisibility = Visibility.Visible; var fileSizeTask = Task.Run(async() => { var size = await CalculateFolderSizeAsync(storageFolder.Path, token); return(size); }); try { var folderSize = await fileSizeTask; ViewModel.ItemSizeBytes = folderSize; ViewModel.ItemSize = $"{ByteSize.FromBytes(folderSize).ToBinaryString().ConvertSizeAbbreviation()} ({ByteSize.FromBytes(folderSize).Bytes:#,##0} {"ItemSizeBytes".GetLocalized()})"; } catch (Exception ex) { App.Logger.Warn(ex, ex.Message); } ViewModel.ItemSizeProgressVisibility = Visibility.Collapsed; SetItemsCountString(); }
public async Task <FilesystemResult <BaseStorageFile> > Create(BaseStorageFolder parentFolder, string fileName) { FilesystemResult <BaseStorageFile> 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(() => StorageFileExtensions.DangerousGetFileFromPathAsync(Template)) .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask()); } if (createdFile) { if (this.Data != null) { //await FileIO.WriteBytesAsync(createdFile.Result, this.Data); // Calls unsupported OpenTransactedWriteAsync using (var fileStream = await createdFile.Result.OpenStreamForWriteAsync()) { await fileStream.WriteAsync(Data, 0, Data.Length); await fileStream.FlushAsync(); } } } return(createdFile); }
public static IAsyncOperation <BaseStorageFolder> GetFolderFromPathAsync(string path) { return(AsyncInfo.Run(async(cancellationToken) => { BaseStorageFolder folder = null; folder ??= await ZipStorageFolder.FromPathAsync(path); folder ??= await FtpStorageFolder.FromPathAsync(path); folder ??= await SystemStorageFolder.FromPathAsync(path); return folder; })); }
public static async Task <bool> CheckBitlockerStatusAsync(BaseStorageFolder rootFolder, string path) { if (rootFolder == null || rootFolder.Properties == null) { return(false); } if (Path.IsPathRooted(path) && Path.GetPathRoot(path) == path) { IDictionary <string, object> extraProperties = await rootFolder.Properties.RetrievePropertiesAsync(new string[] { "System.Volume.BitLockerProtection" }); return((int?)extraProperties["System.Volume.BitLockerProtection"] == 6); // Drive is bitlocker protected and locked } return(false); }
public async void DecompressArchiveToChildFolder() { var selectedItem = associatedInstance?.SlimContentPage?.SelectedItem; if (selectedItem == null) { return; } BaseStorageFile archive = await StorageHelpers.ToStorageItem <BaseStorageFile>(selectedItem.ItemPath); BaseStorageFolder currentFolder = await StorageHelpers.ToStorageItem <BaseStorageFolder>(associatedInstance.FilesystemViewModel.CurrentFolder.ItemPath); BaseStorageFolder destinationFolder = null; if (currentFolder != null) { destinationFolder = await FilesystemTasks.Wrap(() => currentFolder.CreateFolderAsync(Path.GetFileNameWithoutExtension(archive.Path), CreationCollisionOption.OpenIfExists).AsTask()); } if (archive != null && destinationFolder != null) { CancellationTokenSource extractCancellation = new CancellationTokenSource(); PostedStatusBanner banner = App.OngoingTasksViewModel.PostOperationBanner( string.Empty, "ExtractingArchiveText".GetLocalized(), 0, ReturnResult.InProgress, FileOperationType.Extract, extractCancellation); Stopwatch sw = new Stopwatch(); sw.Start(); await ZipHelpers.ExtractArchive(archive, destinationFolder, banner.Progress, extractCancellation.Token); sw.Stop(); banner.Remove(); if (sw.Elapsed.TotalSeconds >= 6) { App.OngoingTasksViewModel.PostBanner( "ExtractingCompleteText".GetLocalized(), "ArchiveExtractionCompletedSuccessfullyText".GetLocalized(), 0, ReturnResult.Success, FileOperationType.Extract); } } }
public async static Task <StorageFolderWithPath> DangerousGetFolderWithPathFromPathAsync(string value, StorageFolderWithPath rootFolder = null, StorageFolderWithPath parentFolder = null) { if (rootFolder != null) { var currComponents = GetDirectoryPathComponents(value); if (rootFolder.Path == value) { return(rootFolder); } else if (parentFolder != null && value.IsSubPathOf(parentFolder.Path)) { var folder = parentFolder.Folder; var prevComponents = GetDirectoryPathComponents(parentFolder.Path); var path = parentFolder.Path; foreach (var component in currComponents.ExceptBy(prevComponents, c => c.Path)) { folder = await folder.GetFolderAsync(component.Title); path = PathNormalization.Combine(path, folder.Name); } return(new StorageFolderWithPath(folder, path)); } else if (value.IsSubPathOf(rootFolder.Path)) { var folder = rootFolder.Folder; var path = rootFolder.Path; foreach (var component in currComponents.Skip(1)) { folder = await folder.GetFolderAsync(component.Title); path = PathNormalization.Combine(path, folder.Name); } return(new StorageFolderWithPath(folder, path)); } } if (parentFolder != null && !Path.IsPathRooted(value)) { // Relative path var fullPath = Path.GetFullPath(Path.Combine(parentFolder.Path, value)); return(new StorageFolderWithPath(await BaseStorageFolder.GetFolderFromPathAsync(fullPath))); } else { return(new StorageFolderWithPath(await BaseStorageFolder.GetFolderFromPathAsync(value))); } }
public async override void GetSpecialProperties() { ViewModel.ItemAttributesVisibility = false; var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(Drive.Path)); BaseStorageFolder diskRoot = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(Drive.Path, item)); if (ViewModel.LoadFileIcon) { if (diskRoot != null) { ViewModel.IconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(diskRoot, 80, ThumbnailMode.SingleItem); } else { ViewModel.IconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.Path, 80); } ViewModel.IconData ??= await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.DeviceID, 80); // For network shortcuts } if (diskRoot == null || diskRoot.Properties == null) { ViewModel.LastSeparatorVisibility = false; return; } try { string freeSpace = "System.FreeSpace"; string capacity = "System.Capacity"; string fileSystem = "System.Volume.FileSystem"; var properties = await diskRoot.Properties.RetrievePropertiesAsync(new[] { freeSpace, capacity, fileSystem }); ViewModel.DriveCapacityValue = (ulong)properties[capacity]; ViewModel.DriveFreeSpaceValue = (ulong)properties[freeSpace]; ViewModel.DriveUsedSpaceValue = ViewModel.DriveCapacityValue - ViewModel.DriveFreeSpaceValue; ViewModel.DriveFileSystem = (string)properties[fileSystem]; } catch (Exception e) { ViewModel.LastSeparatorVisibility = false; App.Logger.Warn(e, e.Message); } }
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 async void DecompressArchiveHere() { BaseStorageFile archive = await StorageHelpers.ToStorageItem <BaseStorageFile>(associatedInstance.SlimContentPage.SelectedItem.ItemPath); BaseStorageFolder currentFolder = await StorageHelpers.ToStorageItem <BaseStorageFolder>(associatedInstance.FilesystemViewModel.CurrentFolder.ItemPath); if (archive != null && currentFolder != null) { CancellationTokenSource extractCancellation = new CancellationTokenSource(); PostedStatusBanner banner = App.OngoingTasksViewModel.PostOperationBanner( string.Empty, "ExtractingArchiveText".GetLocalized(), 0, ReturnResult.InProgress, FileOperationType.Extract, extractCancellation); Stopwatch sw = new Stopwatch(); sw.Start(); await ZipHelpers.ExtractArchive(archive, currentFolder, banner.Progress, extractCancellation.Token); sw.Stop(); banner.Remove(); if (sw.Elapsed.TotalSeconds >= 6) { App.OngoingTasksViewModel.PostBanner( "ExtractingCompleteText".GetLocalized(), "ArchiveExtractionCompletedSuccessfullyText".GetLocalized(), 0, ReturnResult.Success, FileOperationType.Extract); } } }
private static async Task <FilesystemResult> OpenFile(string path, IShellPage associatedInstance, IEnumerable <string> selectItems, ShortcutItem shortcutInfo, bool openViaApplicationPicker = false, string args = default) { var opened = (FilesystemResult)false; bool isHiddenItem = NativeFileOperationsHelper.HasFileAttribute(path, System.IO.FileAttributes.Hidden); bool isShortcutItem = path.EndsWith(".lnk") || path.EndsWith(".url"); // Determine if (isShortcutItem) { if (string.IsNullOrEmpty(shortcutInfo.TargetPath)) { await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args); } else { if (!path.EndsWith(".url")) { StorageFileWithPath childFile = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(shortcutInfo.TargetPath); if (childFile != null) { // Add location to MRU List if (childFile.File is SystemStorageFile) { var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; mostRecentlyUsed.Add(await childFile.File.ToStorageFileAsync(), childFile.Path); } } } await Win32Helpers.InvokeWin32ComponentAsync(shortcutInfo.TargetPath, associatedInstance, $"{args} {shortcutInfo.Arguments}", shortcutInfo.RunAsAdmin, shortcutInfo.WorkingDirectory); } opened = (FilesystemResult)true; } else if (isHiddenItem) { await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args); } else { opened = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(path) .OnSuccess(async childFile => { // Add location to MRU List if (childFile.File is SystemStorageFile) { var mostRecentlyUsed = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList; mostRecentlyUsed.Add(await childFile.File.ToStorageFileAsync(), childFile.Path); } if (openViaApplicationPicker) { LauncherOptions options = new LauncherOptions { DisplayApplicationPicker = true }; if (!await Launcher.LaunchFileAsync(childFile.File, options)) { var connection = await AppServiceConnectionHelper.Instance; if (connection != null) { await connection.SendMessageAsync(new ValueSet() { { "Arguments", "InvokeVerb" }, { "FilePath", path }, { "Verb", "openas" } }); } } } else { //try using launcher first bool launchSuccess = false; BaseStorageFileQueryResult 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) BaseStorageFolder currentFolder = await associatedInstance.FilesystemViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(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 == 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; } var options = new LauncherOptions(); if (currentFolder.AreQueryOptionsSupported(queryOptions)) { fileQueryResult = currentFolder.CreateFileQueryWithOptions(queryOptions); options.NeighboringFilesQuery = fileQueryResult.ToStorageFileQueryResult(); } // Now launch file with options. launchSuccess = await Launcher.LaunchFileAsync(await childFile.File.ToStorageFileAsync(), options); } if (!launchSuccess) { await Win32Helpers.InvokeWin32ComponentAsync(path, associatedInstance, args); } } }); } return(opened); }
public StorageFolderWithPath(BaseStorageFolder folder, string path) { Folder = folder; Path = path; }
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); }
public async void DecompressArchive() { BaseStorageFile archive = await StorageHelpers.ToStorageItem <BaseStorageFile>(associatedInstance.SlimContentPage.SelectedItem.ItemPath); if (archive != null) { DecompressArchiveDialog decompressArchiveDialog = new DecompressArchiveDialog(); DecompressArchiveDialogViewModel decompressArchiveViewModel = new DecompressArchiveDialogViewModel(archive); decompressArchiveDialog.ViewModel = decompressArchiveViewModel; ContentDialogResult option = await decompressArchiveDialog.ShowAsync(); if (option == ContentDialogResult.Primary) { // Check if archive still exists if (!StorageHelpers.Exists(archive.Path)) { return; } CancellationTokenSource extractCancellation = new CancellationTokenSource(); PostedStatusBanner banner = App.OngoingTasksViewModel.PostOperationBanner( string.Empty, "ExtractingArchiveText".GetLocalized(), 0, ReturnResult.InProgress, FileOperationType.Extract, extractCancellation); BaseStorageFolder destinationFolder = decompressArchiveViewModel.DestinationFolder; string destinationFolderPath = decompressArchiveViewModel.DestinationFolderPath; if (destinationFolder == null) { BaseStorageFolder parentFolder = await StorageHelpers.ToStorageItem <BaseStorageFolder>(Path.GetDirectoryName(archive.Path)); destinationFolder = await FilesystemTasks.Wrap(() => parentFolder.CreateFolderAsync(Path.GetFileName(destinationFolderPath), CreationCollisionOption.GenerateUniqueName).AsTask()); } if (destinationFolder == null) { return; // Could not create dest folder } Stopwatch sw = new Stopwatch(); sw.Start(); await ZipHelpers.ExtractArchive(archive, destinationFolder, banner.Progress, extractCancellation.Token); sw.Stop(); banner.Remove(); if (sw.Elapsed.TotalSeconds >= 6) { App.OngoingTasksViewModel.PostBanner( "ExtractingCompleteText".GetLocalized(), "ArchiveExtractionCompletedSuccessfullyText".GetLocalized(), 0, ReturnResult.Success, FileOperationType.Extract); } if (decompressArchiveViewModel.OpenDestinationFolderOnCompletion) { await NavigationHelpers.OpenPath(destinationFolderPath, associatedInstance, FilesystemItemType.Directory); } } } }
public BaseStorageFileQueryResult(BaseStorageFolder folder, QueryOptions options) { Folder = folder; Options = options; }
public StorageFolderWithPath(BaseStorageFolder folder) : this(folder, folder.Path) { }
private static async Task <IReadOnlyList <IStorageItem> > EnumerateFileByFile(BaseStorageFolder rootFolder, uint startFrom, uint itemsToIterate) { var tempList = new List <IStorageItem>(); for (var i = startFrom; i < startFrom + itemsToIterate; i++) { IStorageItem item; try { var results = await rootFolder.GetItemsAsync(i, 1); item = results?.FirstOrDefault(); if (item == null) { break; } } catch (NotImplementedException) { break; } catch (Exception ex) when( ex is UnauthorizedAccessException || ex is FileNotFoundException || (uint)ex.HResult == 0x80070490) // ERROR_NOT_FOUND { continue; } tempList.Add(item); } return(tempList); }
public static async Task <List <ListedItem> > ListEntries( BaseStorageFolder rootFolder, StorageFolderWithPath currentStorageFolder, string returnformat, Type sourcePageType, CancellationToken cancellationToken, int countLimit, Func <List <ListedItem>, Task> intermediateAction, Dictionary <string, BitmapImage> defaultIconPairs = null ) { var sampler = new IntervalSampler(500); var tempList = new List <ListedItem>(); uint count = 0; var firstRound = true; while (true) { IReadOnlyList <IStorageItem> items; uint maxItemsToRetrieve = 300; if (intermediateAction == null) { // without intermediate action increase batches significantly maxItemsToRetrieve = 1000; } else if (firstRound) { maxItemsToRetrieve = 32; firstRound = false; } try { items = await rootFolder.GetItemsAsync(count, maxItemsToRetrieve); if (items == null || items.Count == 0) { break; } } catch (NotImplementedException) { break; } catch (Exception ex) when( ex is UnauthorizedAccessException || ex is FileNotFoundException || (uint)ex.HResult == 0x80070490) // ERROR_NOT_FOUND { // If some unexpected exception is thrown - enumerate this folder file by file - just to be sure items = await EnumerateFileByFile(rootFolder, count, maxItemsToRetrieve); } foreach (var item in items) { if (item.IsOfType(StorageItemTypes.Folder)) { var folder = await AddFolderAsync(item.AsBaseStorageFolder(), currentStorageFolder, returnformat, cancellationToken); if (folder != null) { if (defaultIconPairs?.ContainsKey(string.Empty) ?? false) { folder.SetDefaultIcon(defaultIconPairs[string.Empty]); } tempList.Add(folder); } } else { var fileEntry = await AddFileAsync(item.AsBaseStorageFile(), currentStorageFolder, returnformat, cancellationToken); if (fileEntry != null) { if (defaultIconPairs != null) { if (!string.IsNullOrEmpty(fileEntry.FileExtension)) { var lowercaseExtension = fileEntry.FileExtension.ToLowerInvariant(); if (defaultIconPairs.ContainsKey(lowercaseExtension)) { fileEntry.SetDefaultIcon(defaultIconPairs[lowercaseExtension]); } } } tempList.Add(fileEntry); } } if (cancellationToken.IsCancellationRequested) { break; } } count += maxItemsToRetrieve; if (countLimit > -1 && count >= countLimit) { break; } if (intermediateAction != null && (items.Count == maxItemsToRetrieve || sampler.CheckNow())) { await intermediateAction(tempList); // clear the temporary list every time we do an intermediate action tempList.Clear(); } } return(tempList); }
public StorageFolderWithPath(BaseStorageFolder folder, string path) => (Item, Path) = (folder, path);
public static async Task ExtractArchive(BaseStorageFile archive, BaseStorageFolder destinationFolder, IProgress <float> progressDelegate, CancellationToken cancellationToken) { ZipFile zipFile = await Filesystem.FilesystemTasks.Wrap(async() => new ZipFile(await archive.OpenStreamForReadAsync())); if (zipFile == null) { return; } using (zipFile) { zipFile.IsStreamOwner = true; List <ZipEntry> directoryEntries = new List <ZipEntry>(); List <ZipEntry> fileEntries = new List <ZipEntry>(); foreach (ZipEntry entry in zipFile) { if (entry.IsFile) { fileEntries.Add(entry); } else { directoryEntries.Add(entry); } } if (cancellationToken.IsCancellationRequested) // Check if cancelled { return; } var wnt = new WindowsNameTransform(destinationFolder.Path); var zipEncoding = ZipStorageFolder.DetectFileEncoding(zipFile); var directories = new List <string>(); try { directories.AddRange(directoryEntries.Select((entry) => wnt.TransformDirectory(ZipStorageFolder.DecodeEntryName(entry, zipEncoding)))); directories.AddRange(fileEntries.Select((entry) => Path.GetDirectoryName(wnt.TransformFile(ZipStorageFolder.DecodeEntryName(entry, zipEncoding))))); } catch (InvalidNameException ex) { App.Logger.Warn(ex, $"Error transforming zip names into: {destinationFolder.Path}\n" + $"Directories: {string.Join(", ", directoryEntries.Select(x => x.Name))}\n" + $"Files: {string.Join(", ", fileEntries.Select(x => x.Name))}"); return; } foreach (var dir in directories.Distinct().OrderBy(x => x.Length)) { if (!NativeFileOperationsHelper.CreateDirectoryFromApp(dir, IntPtr.Zero)) { var dirName = destinationFolder.Path; foreach (var component in dir.Substring(destinationFolder.Path.Length).Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) { dirName = Path.Combine(dirName, component); NativeFileOperationsHelper.CreateDirectoryFromApp(dirName, IntPtr.Zero); } } if (cancellationToken.IsCancellationRequested) // Check if canceled { return; } } if (cancellationToken.IsCancellationRequested) // Check if canceled { return; } // Fill files byte[] buffer = new byte[4096]; int entriesAmount = fileEntries.Count; int entriesFinished = 0; foreach (var entry in fileEntries) { if (cancellationToken.IsCancellationRequested) // Check if canceled { return; } if (entry.IsCrypted) { App.Logger.Info($"Skipped encrypted zip entry: {entry.Name}"); continue; // TODO: support password protected archives } string filePath = wnt.TransformFile(ZipStorageFolder.DecodeEntryName(entry, zipEncoding)); var hFile = NativeFileOperationsHelper.CreateFileForWrite(filePath); if (hFile.IsInvalid) { return; // TODO: handle error } // We don't close hFile because FileStream.Dispose() already does that using (FileStream destinationStream = new FileStream(hFile, FileAccess.Write)) { int currentBlockSize = 0; using (Stream entryStream = zipFile.GetInputStream(entry)) { while ((currentBlockSize = await entryStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { await destinationStream.WriteAsync(buffer, 0, currentBlockSize); if (cancellationToken.IsCancellationRequested) // Check if cancelled { return; } } } } entriesFinished++; float percentage = (float)((float)entriesFinished / (float)entriesAmount) * 100.0f; progressDelegate?.Report(percentage); } } }
public StorageFolderWithPath(BaseStorageFolder folder) { Folder = folder; Path = folder.Path; }
public static async Task <ListedItem> AddFolderAsync(BaseStorageFolder folder, StorageFolderWithPath currentStorageFolder, CancellationToken cancellationToken) { var basicProperties = await folder.GetBasicPropertiesAsync(); if (!cancellationToken.IsCancellationRequested) { if (folder is ShortcutStorageFolder linkFolder) { return(new ShortcutItem(folder.FolderRelativeId) { PrimaryItemAttribute = StorageItemTypes.Folder, IsHiddenItem = false, Opacity = 1, FileImage = null, LoadFileIcon = false, ItemNameRaw = folder.DisplayName, ItemDateModifiedReal = basicProperties.DateModified, ItemDateCreatedReal = folder.DateCreated, ItemType = folder.DisplayType, ItemPath = folder.Path, FileSize = null, FileSizeBytes = 0, TargetPath = linkFolder.TargetPath, Arguments = linkFolder.Arguments, WorkingDirectory = linkFolder.WorkingDirectory, RunAsAdmin = linkFolder.RunAsAdmin }); } else if (folder is BinStorageFolder binFolder) { return(new RecycleBinItem(folder.FolderRelativeId) { PrimaryItemAttribute = StorageItemTypes.Folder, ItemNameRaw = folder.DisplayName, ItemDateModifiedReal = basicProperties.DateModified, ItemDateCreatedReal = folder.DateCreated, ItemType = folder.DisplayType, IsHiddenItem = false, Opacity = 1, FileImage = null, LoadFileIcon = false, ItemPath = string.IsNullOrEmpty(folder.Path) ? PathNormalization.Combine(currentStorageFolder.Path, folder.Name) : folder.Path, FileSize = null, FileSizeBytes = 0, ItemDateDeletedReal = binFolder.DateDeleted, ItemOriginalPath = binFolder.OriginalPath, }); } else { return(new ListedItem(folder.FolderRelativeId) { PrimaryItemAttribute = StorageItemTypes.Folder, ItemNameRaw = folder.DisplayName, ItemDateModifiedReal = basicProperties.DateModified, ItemDateCreatedReal = folder.DateCreated, ItemType = folder.DisplayType, IsHiddenItem = false, Opacity = 1, FileImage = null, LoadFileIcon = false, ItemPath = string.IsNullOrEmpty(folder.Path) ? PathNormalization.Combine(currentStorageFolder.Path, folder.Name) : folder.Path, FileSize = null, FileSizeBytes = 0 }); } } return(null); }
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); }