public ZipStorageFolder(BaseStorageFile backingFile) { if (string.IsNullOrEmpty(backingFile.Path)) { throw new ArgumentException("Backing file Path cannot be null"); } Name = System.IO.Path.GetFileName(backingFile.Path.TrimEnd('\\', '/')); Path = backingFile.Path; ContainerPath = backingFile.Path; BackingFile = backingFile; }
public static IAsyncOperation <BaseStorageFile> GetFileFromPathAsync(string path) { return(AsyncInfo.Run(async(cancellationToken) => { BaseStorageFile file = null; file ??= await ZipStorageFile.FromPathAsync(path); file ??= await FtpStorageFile.FromPathAsync(path); file ??= await SystemStorageFile.FromPathAsync(path); return file; })); }
public static IAsyncOperation <BaseStorageFolder> FromStorageFileAsync(BaseStorageFile file) { return(AsyncInfo.Run <BaseStorageFolder>(async(cancellationToken) => { if (await CheckAccess(file)) { return new ZipStorageFolder(file); } return null; })); }
public async static Task <StorageFileWithPath> DangerousGetFileWithPathFromPathAsync(string value, StorageFolderWithPath rootFolder = null, StorageFolderWithPath parentFolder = null) { if (rootFolder != null) { var currComponents = GetDirectoryPathComponents(value); 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).SkipLast(1)) { folder = await folder.GetFolderAsync(component.Title); path = PathNormalization.Combine(path, folder.Name); } var file = await folder.GetFileAsync(currComponents.Last().Title); path = PathNormalization.Combine(path, file.Name); return(new StorageFileWithPath(file, path)); } else if (value.IsSubPathOf(rootFolder.Path)) { var folder = rootFolder.Folder; var path = rootFolder.Path; foreach (var component in currComponents.Skip(1).SkipLast(1)) { folder = await folder.GetFolderAsync(component.Title); path = PathNormalization.Combine(path, folder.Name); } var file = await folder.GetFileAsync(currComponents.Last().Title); path = PathNormalization.Combine(path, file.Name); return(new StorageFileWithPath(file, path)); } } if (parentFolder != null && !Path.IsPathRooted(value)) { // Relative path var fullPath = Path.GetFullPath(Path.Combine(parentFolder.Path, value)); return(new StorageFileWithPath(await BaseStorageFile.GetFileFromPathAsync(fullPath))); } else { return(new StorageFileWithPath(await BaseStorageFile.GetFileFromPathAsync(value))); } }
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 Task SyncPropertyChangesAsync() { BaseStorageFile file = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(Item.ItemPath)); if (file == null) { // Could not access file, can't save properties return; } var failedProperties = ""; foreach (var group in ViewModel.PropertySections) { foreach (FileProperty prop in group) { if (!prop.IsReadOnly && prop.Modified) { var newDict = new Dictionary <string, object>(); newDict.Add(prop.Property, prop.Value); try { if (file.Properties != null) { await file.Properties.SavePropertiesAsync(newDict); } } catch { failedProperties += $"{prop.Name}\n"; } } } } if (!string.IsNullOrWhiteSpace(failedProperties)) { throw new Exception($"The following properties failed to save: {failedProperties}"); } }
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); } } }
/// <summary> /// This function goes through ever read-write property saved, then syncs it /// </summary> /// <returns></returns> public async Task ClearPropertiesAsync() { var failedProperties = new List <string>(); BaseStorageFile file = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(Item.ItemPath)); if (file == null) { return; } foreach (var group in ViewModel.PropertySections) { foreach (FileProperty prop in group) { if (!prop.IsReadOnly) { var newDict = new Dictionary <string, object>(); newDict.Add(prop.Property, null); try { if (file.Properties != null) { await file.Properties.SavePropertiesAsync(newDict); } } catch { failedProperties.Add(prop.Name); } } } } GetSystemFileProperties(); }
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); } } } }
private static async Task <ListedItem> AddFileAsync( BaseStorageFile file, StorageFolderWithPath currentStorageFolder, string dateReturnFormat, CancellationToken cancellationToken ) { IUserSettingsService userSettingsService = Ioc.Default.GetService <IUserSettingsService>(); var basicProperties = await file.GetBasicPropertiesAsync(); // Display name does not include extension var itemName = string.IsNullOrEmpty(file.DisplayName) || userSettingsService.PreferencesSettingsService.ShowFileExtensions ? file.Name : file.DisplayName; var itemModifiedDate = basicProperties.DateModified; var itemCreatedDate = file.DateCreated; var itemPath = string.IsNullOrEmpty(file.Path) ? PathNormalization.Combine(currentStorageFolder.Path, file.Name) : file.Path; var itemSize = ByteSize.FromBytes(basicProperties.Size).ToBinaryString().ConvertSizeAbbreviation(); var itemSizeBytes = basicProperties.Size; var itemType = file.DisplayType; var itemFileExtension = file.FileType; var itemThumbnailImgVis = false; if (cancellationToken.IsCancellationRequested) { return(null); } if (file.Name.EndsWith(".lnk") || file.Name.EndsWith(".url")) { // This shouldn't happen, StorageFile api does not support shortcuts Debug.WriteLine("Something strange: StorageFile api returned a shortcut"); } // TODO: is this needed to be handled here? else if (App.LibraryManager.TryGetLibrary(file.Path, out LibraryLocationItem library)) { return(new LibraryItem(library) { ItemDateModifiedReal = itemModifiedDate, ItemDateCreatedReal = itemCreatedDate, }); } else { return(new ListedItem(file.FolderRelativeId, dateReturnFormat) { PrimaryItemAttribute = StorageItemTypes.File, FileExtension = itemFileExtension, IsHiddenItem = false, Opacity = 1, FileImage = null, LoadFileIcon = itemThumbnailImgVis, ItemName = itemName, ItemDateModifiedReal = itemModifiedDate, ItemDateCreatedReal = itemCreatedDate, ItemType = itemType, ItemPath = itemPath, FileSize = itemSize, FileSizeBytes = (long)itemSizeBytes, }); } return(null); }
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 StorageFileWithPath(BaseStorageFile file, string path) => (Item, Path) = (file, path);
private async Task ExportSettings() { FileSavePicker filePicker = new FileSavePicker(); filePicker.FileTypeChoices.Add("Zip File", new[] { ".zip" }); filePicker.SuggestedFileName = $"Files_{App.AppVersion}"; StorageFile file = await filePicker.PickSaveFileAsync(); if (file != null) { try { var zipFolder = await ZipStorageFolder.FromStorageFileAsync(file); if (zipFolder == null) { return; } var localFolderPath = ApplicationData.Current.LocalFolder.Path; // Export user settings var userSettings = await zipFolder.CreateFileAsync(Constants.LocalSettings.UserSettingsFileName, CreationCollisionOption.ReplaceExisting); string exportSettings = (string)UserSettingsService.ExportSettings(); await userSettings.WriteTextAsync(exportSettings); // Export bundles var bundles = await zipFolder.CreateFileAsync(Constants.LocalSettings.BundlesSettingsFileName, CreationCollisionOption.ReplaceExisting); string exportBundles = (string)BundlesSettingsService.ExportSettings(); await bundles.WriteTextAsync(exportBundles); // Export pinned items var pinnedItems = await BaseStorageFile.GetFileFromPathAsync(Path.Combine(localFolderPath, Constants.LocalSettings.SettingsFolderName, App.SidebarPinnedController.JsonFileName)); await pinnedItems.CopyAsync(zipFolder, pinnedItems.Name, NameCollisionOption.ReplaceExisting); // Export terminals config var terminals = await BaseStorageFile.GetFileFromPathAsync(Path.Combine(localFolderPath, Constants.LocalSettings.SettingsFolderName, App.TerminalController.JsonFileName)); await terminals.CopyAsync(zipFolder, terminals.Name, NameCollisionOption.ReplaceExisting); // Export file tags list and DB var fileTagsList = await zipFolder.CreateFileAsync(Constants.LocalSettings.FileTagSettingsFileName, CreationCollisionOption.ReplaceExisting); string exportTags = (string)FileTagsSettingsService.ExportSettings(); await fileTagsList.WriteTextAsync(exportTags); var fileTagsDB = await zipFolder.CreateFileAsync(Path.GetFileName(FileTagsHelper.FileTagsDbPath), CreationCollisionOption.ReplaceExisting); string exportTagsDB = FileTagsHelper.DbInstance.Export(); await fileTagsDB.WriteTextAsync(exportTagsDB); // Export layout preferences DB var layoutPrefsDB = await zipFolder.CreateFileAsync(Path.GetFileName(FolderSettingsViewModel.LayoutSettingsDbPath), CreationCollisionOption.ReplaceExisting); string exportPrefsDB = FolderSettingsViewModel.DbInstance.Export(); await layoutPrefsDB.WriteTextAsync(exportPrefsDB); } catch (Exception ex) { App.Logger.Warn(ex, "Error exporting settings"); } } }
public StorageFileWithPath(BaseStorageFile file) : this(file, file.Path) { }
public static async Task <ListedItem> AddFileAsync( BaseStorageFile file, StorageFolderWithPath currentStorageFolder, CancellationToken cancellationToken ) { var basicProperties = await file.GetBasicPropertiesAsync(); // Display name does not include extension var itemName = file.Name; var itemModifiedDate = basicProperties.DateModified; var itemCreatedDate = file.DateCreated; var itemPath = string.IsNullOrEmpty(file.Path) ? PathNormalization.Combine(currentStorageFolder.Path, file.Name) : file.Path; var itemSize = basicProperties.Size.ToSizeString(); var itemSizeBytes = basicProperties.Size; var itemType = file.DisplayType; var itemFileExtension = file.FileType; var itemThumbnailImgVis = false; if (cancellationToken.IsCancellationRequested) { return(null); } // TODO: is this needed to be handled here? if (App.LibraryManager.TryGetLibrary(file.Path, out LibraryLocationItem library)) { return(new LibraryItem(library) { ItemDateModifiedReal = itemModifiedDate, ItemDateCreatedReal = itemCreatedDate, }); } else { if (file is ShortcutStorageFile linkFile) { var isUrl = linkFile.Name.EndsWith(".url", StringComparison.OrdinalIgnoreCase); return(new ShortcutItem(file.FolderRelativeId) { PrimaryItemAttribute = StorageItemTypes.File, FileExtension = itemFileExtension, IsHiddenItem = false, Opacity = 1, FileImage = null, LoadFileIcon = itemThumbnailImgVis, LoadWebShortcutGlyph = isUrl, ItemNameRaw = itemName, ItemDateModifiedReal = itemModifiedDate, ItemDateCreatedReal = itemCreatedDate, ItemType = itemType, ItemPath = itemPath, FileSize = itemSize, FileSizeBytes = (long)itemSizeBytes, TargetPath = linkFile.TargetPath, Arguments = linkFile.Arguments, WorkingDirectory = linkFile.WorkingDirectory, RunAsAdmin = linkFile.RunAsAdmin, IsUrl = isUrl, }); } else if (file is BinStorageFile binFile) { return(new RecycleBinItem(file.FolderRelativeId) { PrimaryItemAttribute = StorageItemTypes.File, FileExtension = itemFileExtension, IsHiddenItem = false, Opacity = 1, FileImage = null, LoadFileIcon = itemThumbnailImgVis, ItemNameRaw = itemName, ItemDateModifiedReal = itemModifiedDate, ItemDateCreatedReal = itemCreatedDate, ItemType = itemType, ItemPath = itemPath, FileSize = itemSize, FileSizeBytes = (long)itemSizeBytes, ItemDateDeletedReal = binFile.DateDeleted, ItemOriginalPath = binFile.OriginalPath }); } else { return(new ListedItem(file.FolderRelativeId) { PrimaryItemAttribute = StorageItemTypes.File, FileExtension = itemFileExtension, IsHiddenItem = false, Opacity = 1, FileImage = null, LoadFileIcon = itemThumbnailImgVis, ItemNameRaw = itemName, ItemDateModifiedReal = itemModifiedDate, ItemDateCreatedReal = itemCreatedDate, ItemType = itemType, ItemPath = itemPath, FileSize = itemSize, FileSizeBytes = (long)itemSizeBytes, }); } } return(null); }
public StorageFileWithPath(BaseStorageFile file, string path) { File = file; Path = path; }
/// <summary> /// This function encodes a software bitmap with the specified encoder and saves it to a file /// </summary> /// <param name="softwareBitmap"></param> /// <param name="outputFile"></param> /// <param name="encoderId">The guid of the image encoder type</param> /// <returns></returns> public static async Task SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap, BaseStorageFile outputFile, Guid encoderId) { using IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite); // Create an encoder with the desired format BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, stream); // Set the software bitmap encoder.SetSoftwareBitmap(softwareBitmap); try { await encoder.FlushAsync(); } catch (Exception err) { const int WINCODEC_ERR_UNSUPPORTEDOPERATION = unchecked ((int)0x88982F81); switch (err.HResult) { case WINCODEC_ERR_UNSUPPORTEDOPERATION: // If the encoder does not support writing a thumbnail, then try again // but disable thumbnail generation. encoder.IsThumbnailGenerated = false; break; default: throw; } } if (encoder.IsThumbnailGenerated == false) { await encoder.FlushAsync(); } }
public override async void GetSpecialProperties() { ViewModel.IsReadOnly = NativeFileOperationsHelper.HasFileAttribute( Item.ItemPath, System.IO.FileAttributes.ReadOnly); ViewModel.IsHidden = NativeFileOperationsHelper.HasFileAttribute( Item.ItemPath, System.IO.FileAttributes.Hidden); ViewModel.ItemSizeVisibility = Visibility.Visible; ViewModel.ItemSize = $"{ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation()} ({ByteSize.FromBytes(Item.FileSizeBytes).Bytes:#,##0} {"ItemSizeBytes".GetLocalized()})"; var fileIconData = await FileThumbnailHelper.LoadIconFromPathAsync(Item.ItemPath, 80, Windows.Storage.FileProperties.ThumbnailMode.SingleItem); if (fileIconData != null) { ViewModel.IconData = fileIconData; ViewModel.LoadUnknownTypeGlyph = false; ViewModel.LoadFileIcon = true; } if (Item.IsShortcutItem) { ViewModel.ItemCreatedTimestamp = Item.ItemDateCreated; ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed; ViewModel.LoadLinkIcon = Item.LoadWebShortcutGlyph; if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((ShortcutItem)Item).TargetPath)) { // Can't show any other property return; } } BaseStorageFile file = await AppInstance.FilesystemViewModel.GetFileFromPathAsync((Item as ShortcutItem)?.TargetPath ?? Item.ItemPath); if (file == null) { // Could not access file, can't show any other property return; } if (Item.IsShortcutItem) { // Can't show any other property return; } if (file.Properties != null) { GetOtherProperties(file.Properties); } // Get file MD5 hash var hashAlgTypeName = HashAlgorithmNames.Md5; ViewModel.ItemMD5HashProgressVisibility = Visibility.Visible; ViewModel.ItemMD5HashVisibility = Visibility.Visible; try { ViewModel.ItemMD5Hash = await GetHashForFileAsync(Item, hashAlgTypeName, TokenSource.Token, hashProgress, AppInstance); } catch (Exception ex) { App.Logger.Warn(ex, ex.Message); ViewModel.ItemMD5HashCalcError = true; } }
private async Task <string> GetHashForFileAsync(ListedItem fileItem, string nameOfAlg, CancellationToken token, IProgress <float> progress, IShellPage associatedInstance) { HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(nameOfAlg); BaseStorageFile file = await StorageItemHelpers.ToStorageItem <BaseStorageFile>((fileItem as ShortcutItem)?.TargetPath ?? fileItem.ItemPath, associatedInstance); if (file == null) { return(""); } Stream stream = await FilesystemTasks.Wrap(() => file.OpenStreamForReadAsync()); if (stream == null) { return(""); } uint capacity; var inputStream = stream.AsInputStream(); bool isProgressSupported = false; try { var cap = (long)(0.5 * stream.Length) / 100; if (cap >= uint.MaxValue) { capacity = uint.MaxValue; } else { capacity = Convert.ToUInt32(cap); } isProgressSupported = true; } catch (NotSupportedException) { capacity = 64 * 1024; } Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity); var hash = algorithmProvider.CreateHash(); while (!token.IsCancellationRequested) { await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None); if (buffer.Length > 0) { hash.Append(buffer); } else { break; } if (stream.Length > 0) { progress?.Report(isProgressSupported ? (float)stream.Position / stream.Length * 100.0f : 20); } } inputStream.Dispose(); stream.Dispose(); if (token.IsCancellationRequested) { return(""); } return(CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToLower()); }
public StorageFileWithPath(BaseStorageFile file) { File = file; Path = File.Path; }