Ejemplo n.º 1
0
        public async Task <bool> CreateNewNamedPipe()
        {
            try
            {
                if (ClientStream != null)
                {
                    return(true);
                }

                if (WindowsVersionChecker.IsNewerOrEqual(WindowsVersionChecker.Version.Windows10_2004))
                {
                    await FullTrustExcutorController.Current.RequestCreateNewPipeLine(GUID).ConfigureAwait(true);

                    PipeHandle   = WIN_Native_API.GetHandleFromNamedPipe($"Explorer_And_FullTrustProcess_NamedPipe-{GUID}");
                    ClientStream = new NamedPipeClientStream(PipeDirection.InOut, false, true, PipeHandle);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return(false);
            }
        }
Ejemplo n.º 2
0
        public async virtual Task <FileStream> GetFileStreamFromFileAsync(AccessMode Mode)
        {
            try
            {
                if (WIN_Native_API.CreateFileStreamFromExistingPath(Path, Mode) is FileStream Stream)
                {
                    return(Stream);
                }
                else
                {
                    if (await GetStorageItemAsync().ConfigureAwait(true) is StorageFile File)
                    {
                        SafeFileHandle Handle = File.GetSafeFileHandle();

                        return(new FileStream(Handle, FileAccess.ReadWrite));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Could not create a new file stream");
                return(null);
            }
        }
Ejemplo n.º 3
0
        public override async Task <IStorageItem> GetStorageItem()
        {
            if (StorageItem == null)
            {
                try
                {
                    Package = await FullTrustProcessController.Current.GetHyperlinkRelatedInformationAsync(InternalPathString).ConfigureAwait(false);

                    if (WIN_Native_API.CheckExist(LinkTargetPath))
                    {
                        if (WIN_Native_API.CheckType(LinkTargetPath) == StorageItemTypes.Folder)
                        {
                            return(StorageItem = await StorageFolder.GetFolderFromPathAsync(LinkTargetPath));
                        }
                        else
                        {
                            return(StorageItem = await StorageFile.GetFileFromPathAsync(LinkTargetPath));
                        }
                    }
                    else
                    {
                        return(StorageItem = null);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"Could not get hyperlink file, path: {InternalPathString}");
                    return(StorageItem = null);
                }
            }
            else
            {
                return(StorageItem);
            }
        }
 public void StopWatchDirectory()
 {
     if (WatchPtr != IntPtr.Zero)
     {
         WIN_Native_API.StopDirectoryWatcher(ref WatchPtr);
     }
 }
Ejemplo n.º 5
0
        public async Task <List <FileSystemStorageItemBase> > GetChildItemsAsync(bool IncludeHiddenItems, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(WIN_Native_API.GetStorageItems(Path, IncludeHiddenItems, Filter));
            }
            else
            {
                LogTracer.Log($"Native API could not enum subitems in path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    if (await GetStorageItemAsync().ConfigureAwait(true) is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Shallow,
                            IndexerOption = IndexerOption.UseIndexerWhenAvailable
                        };
                        Options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 150, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
                        Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        uint Count = await Query.GetItemCountAsync();

                        List <FileSystemStorageItemBase> Result = new List <FileSystemStorageItemBase>(Convert.ToInt32(Count));

                        for (uint i = 0; i < Count; i += 30)
                        {
                            IReadOnlyList <IStorageItem> CurrentList = await Query.GetItemsAsync(i, 30);

                            foreach (IStorageItem Item in CurrentList.Where((Item) => (Item.IsOfType(StorageItemTypes.Folder) && Filter.HasFlag(ItemFilters.Folder)) || (Item.IsOfType(StorageItemTypes.File) && Filter.HasFlag(ItemFilters.File))))
                            {
                                if (Item is StorageFolder SubFolder)
                                {
                                    Result.Add(new FileSystemStorageFolder(SubFolder, await SubFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFolder.GetModifiedTimeAsync().ConfigureAwait(true)));
                                }
                                else if (Item is StorageFile SubFile)
                                {
                                    Result.Add(new FileSystemStorageFile(SubFile, await SubFile.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFile.GetSizeRawDataAsync().ConfigureAwait(true), await SubFile.GetModifiedTimeAsync().ConfigureAwait(true)));
                                }
                            }
                        }

                        return(Result);
                    }
                    else
                    {
                        return(new List <FileSystemStorageItemBase>(0));
                    }
                }
                catch
                {
                    LogTracer.Log($"UWP API could not enum subitems in path: \"{Path}\"");
                    return(new List <FileSystemStorageItemBase>(0));
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <ulong> GetFolderSizeAsync(CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(await Task.Run(() =>
                {
                    return WIN_Native_API.CalulateSize(Path, CancelToken);
                }));
            }
            else
            {
                try
                {
                    LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Deep,
                            IndexerOption = IndexerOption.UseIndexerWhenAvailable
                        };
                        Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size" });

                        StorageFileQueryResult Query = Folder.CreateFileQueryWithOptions(Options);

                        uint FileCount = await Query.GetItemCountAsync();

                        ulong TotalSize = 0;

                        for (uint Index = 0; Index < FileCount && !CancelToken.IsCancellationRequested; Index += 50)
                        {
                            foreach (StorageFile File in await Query.GetFilesAsync(Index, 50))
                            {
                                TotalSize += await File.GetSizeRawDataAsync().ConfigureAwait(false);

                                if (CancelToken.IsCancellationRequested)
                                {
                                    break;
                                }
                            }
                        }

                        return(TotalSize);
                    }
                    else
                    {
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{nameof(GetFolderSizeAsync)} failed for uwp API");
                    return(0);
                }
            }
        }
Ejemplo n.º 7
0
        public void StartWatchDirectory(string Path)
        {
            if (!string.IsNullOrWhiteSpace(Path))
            {
                CurrentLocation = Path;

                StopWatchDirectory();

                WatchPtr = WIN_Native_API.CreateDirectoryWatcher(Path, Added, Removed, Renamed, Modified);
            }
        }
        public static async Task <FileSystemStorageItemBase> OpenAsync(string Path)
        {
            if (System.IO.Path.GetPathRoot(Path) != Path && WIN_Native_API.GetStorageItem(Path) is FileSystemStorageItemBase Item)
            {
                return(Item);
            }
            else
            {
                LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    string DirectoryPath = System.IO.Path.GetDirectoryName(Path);

                    if (string.IsNullOrEmpty(DirectoryPath))
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(Path);

                        return(new FileSystemStorageFolder(Folder, await Folder.GetThumbnailBitmapAsync(), await Folder.GetModifiedTimeAsync()));
                    }
                    else
                    {
                        StorageFolder ParentFolder = await StorageFolder.GetFolderFromPathAsync(DirectoryPath);

                        switch (await ParentFolder.TryGetItemAsync(System.IO.Path.GetFileName(Path)))
                        {
                        case StorageFolder Folder:
                        {
                            return(new FileSystemStorageFolder(Folder, await Folder.GetThumbnailBitmapAsync(), await Folder.GetModifiedTimeAsync()));
                        }

                        case StorageFile File:
                        {
                            return(new FileSystemStorageFile(File, await File.GetThumbnailBitmapAsync(), await File.GetSizeRawDataAsync(), await File.GetModifiedTimeAsync()));
                        }

                        default:
                        {
                            LogTracer.Log($"UWP storage API could not found the path: \"{Path}\"");
                            return(null);
                        }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"UWP storage API could not found the path: \"{Path}\"");
                    return(null);
                }
            }
        }
Ejemplo n.º 9
0
        public static async Task <FileSystemStorageItemBase> OpenAsync(string Path)
        {
            if (WIN_Native_API.CheckLocationAvailability(System.IO.Path.GetDirectoryName(Path)))
            {
                return(WIN_Native_API.GetStorageItem(Path));
            }
            else
            {
                LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    string DirectoryPath = System.IO.Path.GetDirectoryName(Path);

                    if (string.IsNullOrEmpty(DirectoryPath))
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(Path);

                        return(await CreateFromStorageItemAsync(Folder));
                    }
                    else
                    {
                        StorageFolder ParentFolder = await StorageFolder.GetFolderFromPathAsync(DirectoryPath);

                        switch (await ParentFolder.TryGetItemAsync(System.IO.Path.GetFileName(Path)))
                        {
                        case StorageFolder Folder:
                        {
                            return(await CreateFromStorageItemAsync(Folder));
                        }

                        case StorageFile File:
                        {
                            return(await CreateFromStorageItemAsync(File));
                        }

                        default:
                        {
                            LogTracer.Log($"UWP storage API could not found the path: \"{Path}\"");
                            return(null);
                        }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"UWP storage API could not found the path: \"{Path}\"");
                    return(null);
                }
            }
        }
Ejemplo n.º 10
0
        public RecycleStorageItem(string ActualPath, string OriginPath, StorageItemTypes StorageType, DateTimeOffset CreateTime)
        {
            this.OriginPath  = OriginPath;
            this.StorageType = StorageType;

            ModifiedTimeRaw = CreateTime.ToLocalTime();

            if (StorageType == StorageItemTypes.File)
            {
                SizeRaw = WIN_Native_API.CalculateFileSize(ActualPath);
            }

            InternalPathString = ActualPath;
        }
Ejemplo n.º 11
0
        public void StartWatchDirectory(string Path)
        {
            if (!string.IsNullOrWhiteSpace(Path))
            {
                CurrentLocation = Path;

                if (WatchPtr != IntPtr.Zero)
                {
                    WIN_Native_API.StopDirectoryWatcher(ref WatchPtr);
                }

                WatchPtr = WIN_Native_API.CreateDirectoryWatcher(Path, Added, Removed, Renamed, Modified);
            }
        }
Ejemplo n.º 12
0
        public override Task Update()
        {
            if (WIN_Native_API.GetStorageItems(InternalPathString).FirstOrDefault() is HyperlinkStorageItem HItem)
            {
                SizeRaw         = HItem.SizeRaw;
                ModifiedTimeRaw = HItem.ModifiedTimeRaw;
            }

            OnPropertyChanged(nameof(Name));
            OnPropertyChanged(nameof(ModifiedTime));
            OnPropertyChanged(nameof(DisplayType));
            OnPropertyChanged(nameof(Size));

            return(Task.CompletedTask);
        }
Ejemplo n.º 13
0
        public static async Task UpdateAllSubNodeAsync(this TreeViewNode Node)
        {
            if (Node == null)
            {
                throw new ArgumentNullException(nameof(Node), "Node could not be null");
            }

            if (Node.Children.Count > 0)
            {
                List <string> FolderList = WIN_Native_API.GetStorageItemsAndReturnPath((Node.Content as TreeViewNodeContent).Path, SettingControl.IsDisplayHiddenItem, ItemFilters.Folder);
                List <string> PathList   = Node.Children.Select((Item) => (Item.Content as TreeViewNodeContent).Path).ToList();
                List <string> AddList    = FolderList.Except(PathList).ToList();
                List <string> RemoveList = PathList.Except(FolderList).ToList();

                foreach (string AddPath in AddList)
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                    {
                        Node.Children.Add(new TreeViewNode
                        {
                            Content = new TreeViewNodeContent(AddPath),
                            HasUnrealizedChildren = WIN_Native_API.CheckContainsAnyItem(AddPath, ItemFilters.Folder),
                            IsExpanded            = false
                        });
                    });
                }

                foreach (string RemovePath in RemoveList)
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                    {
                        if (Node.Children.Where((Item) => Item.Content is TreeViewNodeContent).FirstOrDefault((Item) => (Item.Content as TreeViewNodeContent).Path.Equals(RemovePath, StringComparison.OrdinalIgnoreCase)) is TreeViewNode RemoveNode)
                        {
                            Node.Children.Remove(RemoveNode);
                        }
                    });
                }

                foreach (TreeViewNode SubNode in Node.Children)
                {
                    await SubNode.UpdateAllSubNodeAsync().ConfigureAwait(true);
                }
            }
            else
            {
                Node.HasUnrealizedChildren = WIN_Native_API.CheckContainsAnyItem((Node.Content as TreeViewNodeContent).Path, ItemFilters.Folder);
            }
        }
Ejemplo n.º 14
0
        public override async Task Replace(string NewPath)
        {
            if (WIN_Native_API.GetStorageItems(NewPath).FirstOrDefault() is HyperlinkStorageItem HItem)
            {
                InternalPathString = HItem.Path;
                SizeRaw            = HItem.SizeRaw;
                ModifiedTimeRaw    = HItem.ModifiedTimeRaw;
                StorageItem        = null;
                _ = await GetStorageItem().ConfigureAwait(true);
            }

            OnPropertyChanged(nameof(Name));
            OnPropertyChanged(nameof(DisplayType));
            OnPropertyChanged(nameof(Size));
            OnPropertyChanged(nameof(ModifiedTime));
        }
        public async Task <List <RecycleStorageItem> > GetRecycleBinItemsAsync()
        {
            try
            {
                IsNowHasAnyActionExcuting = true;

                if (await TryConnectToFullTrustExutor().ConfigureAwait(true))
                {
                    ValueSet Value = new ValueSet
                    {
                        { "ExcuteType", ExcuteType_Get_RecycleBinItems }
                    };

                    AppServiceResponse Response = await Connection.SendMessageAsync(Value);

                    if (Response.Status == AppServiceResponseStatus.Success && !Response.Message.ContainsKey("Error") && !string.IsNullOrEmpty(Convert.ToString(Response.Message["RecycleBinItems_Json_Result"])))
                    {
                        List <Dictionary <string, string> > Items  = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(Convert.ToString(Response.Message["RecycleBinItems_Json_Result"]));
                        List <RecycleStorageItem>           Result = new List <RecycleStorageItem>(Items.Count);

                        foreach (Dictionary <string, string> PropertyDic in Items)
                        {
                            FileSystemStorageItem Item = WIN_Native_API.GetStorageItems(PropertyDic["ActualPath"]).FirstOrDefault();
                            Result.Add(new RecycleStorageItem(Item, PropertyDic["OriginPath"], DateTime.FromBinary(Convert.ToInt64(PropertyDic["CreateTime"]))));
                        }

                        return(Result);
                    }
                    else
                    {
                        return(new List <RecycleStorageItem>(0));
                    }
                }
                else
                {
                    return(new List <RecycleStorageItem>(0));
                }
            }
            catch
            {
                return(new List <RecycleStorageItem>(0));
            }
            finally
            {
                IsNowHasAnyActionExcuting = false;
            }
        }
Ejemplo n.º 16
0
        public static async Task <bool> CheckExistAsync(string Path)
        {
            if (!string.IsNullOrEmpty(Path) && System.IO.Path.IsPathRooted(Path))
            {
                if (WIN_Native_API.CheckLocationAvailability(System.IO.Path.GetDirectoryName(Path)))
                {
                    return(WIN_Native_API.CheckExist(Path));
                }
                else
                {
                    try
                    {
                        string DirectoryPath = System.IO.Path.GetDirectoryName(Path);

                        if (string.IsNullOrEmpty(DirectoryPath))
                        {
                            await StorageFolder.GetFolderFromPathAsync(Path);

                            return(true);
                        }
                        else
                        {
                            StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(DirectoryPath);

                            if (await Folder.TryGetItemAsync(System.IO.Path.GetFileName(Path)) != null)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "CheckExist threw an exception");
                        return(false);
                    }
                }
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 17
0
        public async Task <bool> CreateNewNamedPipeAsync()
        {
            try
            {
                if (ClientStream != null)
                {
                    if (!ClientStream.IsConnected)
                    {
                        ClientStream.Dispose();
                        ClientStream = null;
                        PipeHandle.Dispose();
                        PipeHandle = null;

                        GUID = Guid.NewGuid();
                    }
                    else
                    {
                        return(true);
                    }
                }

                if (WindowsVersionChecker.IsNewerOrEqual(Version.Windows10_2004))
                {
                    await Controller.RequestCreateNewPipeLineAsync(GUID).ConfigureAwait(true);

                    PipeHandle = WIN_Native_API.GetHandleFromNamedPipe($"Explorer_And_FullTrustProcess_NamedPipe-{GUID}");

                    ClientStream = new NamedPipeClientStream(PipeDirection.InOut, false, true, PipeHandle);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"{ nameof(CreateNewNamedPipeAsync)} throw an error");
                return(false);
            }
        }
        public async Task <bool> CheckContainsAnyItemAsync(bool IncludeHiddenItem = false, bool IncludeSystemItem = false, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(await Task.Run(() =>
                {
                    return WIN_Native_API.CheckContainsAnyItem(Path, IncludeHiddenItem, IncludeSystemItem, Filter);
                }));
            }
            else
            {
                LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        if (Filter.HasFlag(ItemFilters.File))
                        {
                            return((await Folder.GetFilesAsync(CommonFileQuery.DefaultQuery, 0, 1)).Any());
                        }

                        if (Filter.HasFlag(ItemFilters.Folder))
                        {
                            return((await Folder.GetFoldersAsync(CommonFolderQuery.DefaultQuery, 0, 1)).Any());
                        }
                    }

                    return(false);
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{nameof(CheckContainsAnyItemAsync)} failed for uwp API");
                    return(false);
                }
            }
        }
Ejemplo n.º 19
0
        private async void Modified(string Path)
        {
            if (!WIN_Native_API.CheckIfHidden(Path) || IsDisplayHiddenItem)
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
                {
                    await Locker.WaitAsync().ConfigureAwait(true);

                    try
                    {
                        if (CurrentCollection.FirstOrDefault((Item) => Item.Path.Equals(Path, StringComparison.OrdinalIgnoreCase)) is FileSystemStorageItemBase Item)
                        {
                            await Item.Update().ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, $"{ nameof(StorageAreaWatcher)}: Modify item to collection failed");
                    }
                    finally
                    {
                        Locker.Release();
                    }
                });
Ejemplo n.º 20
0
        public async IAsyncEnumerable <FileSystemStorageItemBase> SearchAsync(string SearchWord, bool SearchInSubFolders = false, bool IncludeHiddenItem = false, bool IsRegexExpresstion = false, bool IgnoreCase = true, [EnumeratorCancellation] CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                List <FileSystemStorageItemBase> SearchResult = await Task.Run(() =>
                {
                    return(WIN_Native_API.Search(Path, SearchWord, SearchInSubFolders, IncludeHiddenItem, IsRegexExpresstion, IgnoreCase, CancelToken));
                });

                foreach (FileSystemStorageItemBase Item in SearchResult)
                {
                    yield return(Item);

                    if (CancelToken.IsCancellationRequested)
                    {
                        yield break;
                    }
                }
            }
            else
            {
                if (await GetStorageItemAsync().ConfigureAwait(true) is StorageFolder Folder)
                {
                    QueryOptions Options = new QueryOptions
                    {
                        FolderDepth   = SearchInSubFolders ? FolderDepth.Deep : FolderDepth.Shallow,
                        IndexerOption = IndexerOption.UseIndexerWhenAvailable
                    };
                    Options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 150, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
                    Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" });

                    if (!IsRegexExpresstion)
                    {
                        Options.ApplicationSearchFilter = $"System.FileName:*{SearchWord}*";
                    }

                    StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                    uint FileCount = await Query.GetItemCountAsync();

                    for (uint Index = 0; Index < FileCount && !CancelToken.IsCancellationRequested; Index += 50)
                    {
                        IEnumerable <IStorageItem> Result = IsRegexExpresstion
                                                            ? (await Query.GetItemsAsync(Index, 50)).Where((Item) => Regex.IsMatch(Item.Name, SearchWord, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                                                            : (await Query.GetItemsAsync(Index, 50)).Where((Item) => Item.Name.Contains(SearchWord, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));

                        foreach (IStorageItem Item in Result)
                        {
                            switch (Item)
                            {
                            case StorageFolder SubFolder:
                            {
                                yield return(new FileSystemStorageFolder(SubFolder, await SubFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFolder.GetModifiedTimeAsync().ConfigureAwait(true)));

                                break;
                            }

                            case StorageFile SubFile:
                            {
                                yield return(new FileSystemStorageFile(SubFile, await SubFile.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFile.GetSizeRawDataAsync().ConfigureAwait(true), await SubFile.GetModifiedTimeAsync().ConfigureAwait(true)));

                                break;
                            }
                            }

                            if (CancelToken.IsCancellationRequested)
                            {
                                yield break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 21
0
        public override async IAsyncEnumerable <FileSystemStorageItemBase> SearchAsync(string SearchWord, bool SearchInSubFolders = false, bool IncludeHiddenItem = false, bool IncludeSystemItem = false, bool IsRegexExpresstion = false, bool IgnoreCase = true, [EnumeratorCancellation] CancellationToken CancelToken = default)
        {
            foreach (DriveDataBase Drive in CommonAccessCollection.DriveList)
            {
                if (WIN_Native_API.CheckLocationAvailability(Drive.Path))
                {
                    foreach (FileSystemStorageItemBase Item in await Task.Factory.StartNew(() => WIN_Native_API.Search(Drive.Path, SearchWord, SearchInSubFolders, IncludeHiddenItem, IncludeSystemItem, IsRegexExpresstion, IgnoreCase, CancelToken), TaskCreationOptions.LongRunning))
                    {
                        yield return(Item);
                    }
                }
                else
                {
                    if (Drive.DriveFolder != null)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Shallow,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 150, ThumbnailOptions.UseCurrentScale);
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.FileName", "System.Size", "System.DateModified", "System.DateCreated" });

                        StorageItemQueryResult Query = Drive.DriveFolder.CreateItemQueryWithOptions(Options);

                        for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 50)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(Index, 50).AsTask(CancelToken);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in IsRegexExpresstion
                                                              ? ReadOnlyItemList.AsParallel().Where((Item) => Regex.IsMatch(Item.Name, SearchWord, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                                                              : ReadOnlyItemList.AsParallel().Where((Item) => Item.Name.Contains(SearchWord, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)))
                                {
                                    if (CancelToken.IsCancellationRequested)
                                    {
                                        yield break;
                                    }

                                    switch (Item)
                                    {
                                    case StorageFolder SubFolder:
                                    {
                                        yield return(await CreatedByStorageItemAsync(SubFolder));

                                        break;
                                    }

                                    case StorageFile SubFile:
                                    {
                                        yield return(await CreatedByStorageItemAsync(SubFile));

                                        break;
                                    }
                                    }
                                }

                                if (SearchInSubFolders)
                                {
                                    foreach (StorageFolder Item in ReadOnlyItemList.OfType <StorageFolder>())
                                    {
                                        if (CancelToken.IsCancellationRequested)
                                        {
                                            yield break;
                                        }

                                        FileSystemStorageFolder FSubFolder = await CreatedByStorageItemAsync(Item);

                                        await foreach (FileSystemStorageItemBase FSubItem in FSubFolder.SearchAsync(SearchWord, SearchInSubFolders, IncludeHiddenItem, IncludeSystemItem, IsRegexExpresstion, IgnoreCase, CancelToken))
                                        {
                                            if (CancelToken.IsCancellationRequested)
                                            {
                                                yield break;
                                            }

                                            yield return(FSubItem);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public static async Task <FileSystemStorageItemBase> CreateAsync(string Path, StorageItemTypes ItemTypes, CreateOption Option)
        {
            switch (ItemTypes)
            {
            case StorageItemTypes.File:
            {
                if (WIN_Native_API.CreateFileFromPath(Path, Option, out string NewPath))
                {
                    return(await OpenAsync(NewPath));
                }
                else
                {
                    LogTracer.Log($"Native API could not create file: \"{Path}\", fall back to UWP storage API");

                    try
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(Path));

                        switch (Option)
                        {
                        case CreateOption.GenerateUniqueName:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.GenerateUniqueName);

                            return(await CreateFromStorageItemAsync(NewFile));
                        }

                        case CreateOption.OpenIfExist:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.OpenIfExists);

                            return(await CreateFromStorageItemAsync(NewFile));
                        }

                        case CreateOption.ReplaceExisting:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.ReplaceExisting);

                            return(await CreateFromStorageItemAsync(NewFile));
                        }

                        default:
                        {
                            return(null);
                        }
                        }
                    }
                    catch
                    {
                        LogTracer.Log($"UWP storage API could not create file: \"{Path}\"");
                        return(null);
                    }
                }
            }

            case StorageItemTypes.Folder:
            {
                if (WIN_Native_API.CreateDirectoryFromPath(Path, Option, out string NewPath))
                {
                    return(await OpenAsync(NewPath));
                }
                else
                {
                    LogTracer.Log($"Native API could not create file: \"{Path}\", fall back to UWP storage API");

                    try
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(Path));

                        switch (Option)
                        {
                        case CreateOption.GenerateUniqueName:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.GenerateUniqueName);

                            return(await CreateFromStorageItemAsync(NewFolder));
                        }

                        case CreateOption.OpenIfExist:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.OpenIfExists);

                            return(await CreateFromStorageItemAsync(NewFolder));
                        }

                        case CreateOption.ReplaceExisting:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.ReplaceExisting);

                            return(await CreateFromStorageItemAsync(NewFolder));
                        }

                        default:
                        {
                            return(null);
                        }
                        }
                    }
                    catch
                    {
                        LogTracer.Log($"UWP storage API could not create folder: \"{Path}\"");
                        return(null);
                    }
                }
            }

            default:
            {
                return(null);
            }
            }
        }
        public async Task <FileSystemStorageItemBase> DecryptAsync(string ExportFolderPath, string Key, CancellationToken CancelToken = default)
        {
            if (string.IsNullOrWhiteSpace(ExportFolderPath))
            {
                throw new ArgumentNullException(nameof(ExportFolderPath), "ExportFolder could not be null");
            }

            if (string.IsNullOrEmpty(Key))
            {
                throw new ArgumentNullException(nameof(Key), "Key could not be null or empty");
            }

            using (SecureString Secure = SecureAccessProvider.GetFileEncryptionAesIV(Package.Current))
            {
                IntPtr Bstr = Marshal.SecureStringToBSTR(Secure);
                string IV   = Marshal.PtrToStringBSTR(Bstr);
                string DecryptedFilePath = string.Empty;

                try
                {
                    using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider
                    {
                        Mode = CipherMode.CBC,
                        Padding = PaddingMode.Zeros,
                        IV = Encoding.UTF8.GetBytes(IV)
                    })
                    {
                        using (FileStream EncryptFileStream = GetFileStreamFromFile(AccessMode.Read))
                        {
                            StringBuilder Builder = new StringBuilder();

                            using (StreamReader Reader = new StreamReader(EncryptFileStream, Encoding.UTF8, true, 64, true))
                            {
                                for (int Count = 0; Reader.Peek() >= 0; Count++)
                                {
                                    if (Count > 64)
                                    {
                                        throw new FileDamagedException("File damaged, could not be decrypted");
                                    }

                                    char NextChar = (char)Reader.Read();

                                    if (Builder.Length > 0 && NextChar == '$')
                                    {
                                        Builder.Append(NextChar);
                                        break;
                                    }
                                    else
                                    {
                                        Builder.Append(NextChar);
                                    }
                                }
                            }

                            string RawInfoData = Builder.ToString();

                            if (string.IsNullOrWhiteSpace(RawInfoData))
                            {
                                throw new FileDamagedException("File damaged, could not be decrypted");
                            }
                            else
                            {
                                if (RawInfoData.Split('$', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() is string InfoData)
                                {
                                    string[] InfoGroup = InfoData.Split('|');

                                    if (InfoGroup.Length == 2)
                                    {
                                        string FileType = InfoGroup[1];

                                        AES.KeySize = Convert.ToInt32(InfoGroup[0]);

                                        int KeyLengthNeed = AES.KeySize / 8;

                                        AES.Key = Key.Length > KeyLengthNeed?Encoding.UTF8.GetBytes(Key.Substring(0, KeyLengthNeed)) : Encoding.UTF8.GetBytes(Key.PadRight(KeyLengthNeed, '0'));

                                        DecryptedFilePath = System.IO.Path.Combine(ExportFolderPath, $"{System.IO.Path.GetFileNameWithoutExtension(Name)}{FileType}");

                                        if (await CreateAsync(DecryptedFilePath, StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageItemBase Item)
                                        {
                                            using (FileStream DecryptFileStream = Item.GetFileStreamFromFile(AccessMode.Exclusive))
                                                using (ICryptoTransform Decryptor = AES.CreateDecryptor(AES.Key, AES.IV))
                                                {
                                                    EncryptFileStream.Seek(RawInfoData.Length, SeekOrigin.Begin);

                                                    byte[] PasswordConfirm = new byte[16];

                                                    await EncryptFileStream.ReadAsync(PasswordConfirm, 0, PasswordConfirm.Length).ConfigureAwait(false);

                                                    if (Encoding.UTF8.GetString(Decryptor.TransformFinalBlock(PasswordConfirm, 0, PasswordConfirm.Length)) == "PASSWORD_CORRECT")
                                                    {
                                                        using (CryptoStream TransformStream = new CryptoStream(EncryptFileStream, Decryptor, CryptoStreamMode.Read))
                                                        {
                                                            await TransformStream.CopyToAsync(DecryptFileStream, 2048, CancelToken).ConfigureAwait(false);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        throw new PasswordErrorException("Password is not correct");
                                                    }
                                                }

                                            return(await OpenAsync(DecryptedFilePath, ItemFilters.File).ConfigureAwait(false));
                                        }
                                        else
                                        {
                                            throw new Exception("Could not create a new file");
                                        }
                                    }
                                    else
                                    {
                                        throw new FileDamagedException("File damaged, could not be decrypted");
                                    }
                                }
                                else
                                {
                                    throw new FileDamagedException("File damaged, could not be decrypted");
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    if (!string.IsNullOrEmpty(DecryptedFilePath))
                    {
                        WIN_Native_API.DeleteFromPath(DecryptedFilePath);
                    }

                    throw;
                }
                finally
                {
                    Marshal.ZeroFreeBSTR(Bstr);
                    unsafe
                    {
                        fixed(char *ClearPtr = IV)
                        {
                            for (int i = 0; i < IV.Length; i++)
                            {
                                ClearPtr[i] = '\0';
                            }
                        }
                    }
                }
            }
        }
        public async Task <List <FileSystemStorageItemBase> > GetChildItemsAsync(bool IncludeHiddenItems, bool IncludeSystemItem, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(WIN_Native_API.GetStorageItems(Path, IncludeHiddenItems, IncludeSystemItem, Filter));
            }
            else
            {
                LogTracer.Log($"Native API could not enum subitems in path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Shallow,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 150, ThumbnailOptions.UseCurrentScale);
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        List <FileSystemStorageItemBase> Result = new List <FileSystemStorageItemBase>();

                        for (uint i = 0; ; i += 25)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(i, 25);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in ReadOnlyItemList.Where((Item) => (Item.IsOfType(StorageItemTypes.Folder) && Filter.HasFlag(ItemFilters.Folder)) || (Item.IsOfType(StorageItemTypes.File) && Filter.HasFlag(ItemFilters.File))))
                                {
                                    if (Item is StorageFolder SubFolder)
                                    {
                                        Result.Add(new FileSystemStorageFolder(SubFolder, await SubFolder.GetModifiedTimeAsync()));
                                    }
                                    else if (Item is StorageFile SubFile)
                                    {
                                        Result.Add(await CreateFromStorageItemAsync(SubFile));
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(Result);
                    }
                    else
                    {
                        return(new List <FileSystemStorageItemBase>(0));
                    }
                }
                catch
                {
                    LogTracer.Log($"UWP API could not enum subitems in path: \"{Path}\"");
                    return(new List <FileSystemStorageItemBase>(0));
                }
            }
        }
        public async IAsyncEnumerable <FileSystemStorageItemBase> SearchAsync(string SearchWord, bool SearchInSubFolders = false, bool IncludeHiddenItem = false, bool IncludeSystemItem = false, bool IsRegexExpresstion = false, bool IgnoreCase = true, [EnumeratorCancellation] CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                foreach (FileSystemStorageItemBase Item in await Task.Run(() => WIN_Native_API.Search(Path, SearchWord, SearchInSubFolders, IncludeHiddenItem, IncludeSystemItem, IsRegexExpresstion, IgnoreCase, CancelToken)))
                {
                    yield return(Item);
                }
            }
            else
            {
                if (await GetStorageItemAsync() is StorageFolder Folder)
                {
                    QueryOptions Options = new QueryOptions
                    {
                        FolderDepth   = SearchInSubFolders ? FolderDepth.Deep : FolderDepth.Shallow,
                        IndexerOption = IndexerOption.DoNotUseIndexer
                    };
                    Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 150, ThumbnailOptions.UseCurrentScale);
                    Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.FileName", "System.Size", "System.DateModified", "System.DateCreated" });

                    if (!IsRegexExpresstion)
                    {
                        Options.ApplicationSearchFilter = $"System.FileName:~=\"{SearchWord}\"";
                    }

                    StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                    for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 25)
                    {
                        IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(Index, 25);

                        if (ReadOnlyItemList.Count > 0)
                        {
                            IEnumerable <IStorageItem> Result = IsRegexExpresstion
                                                                ? ReadOnlyItemList.Where((Item) => Regex.IsMatch(Item.Name, SearchWord, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                                                                : ReadOnlyItemList.Where((Item) => Item.Name.Contains(SearchWord, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));

                            foreach (IStorageItem Item in Result)
                            {
                                if (CancelToken.IsCancellationRequested)
                                {
                                    yield break;
                                }

                                switch (Item)
                                {
                                case StorageFolder SubFolder:
                                {
                                    yield return(new FileSystemStorageFolder(SubFolder, await SubFolder.GetModifiedTimeAsync()));

                                    break;
                                }

                                case StorageFile SubFile:
                                {
                                    yield return(await CreateFromStorageItemAsync(SubFile));

                                    break;
                                }
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
        public async Task <(uint, uint)> GetFolderAndFileNumAsync(CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(await Task.Run(() =>
                {
                    return WIN_Native_API.CalculateFolderAndFileCount(Path, CancelToken);
                }));
            }
            else
            {
                try
                {
                    LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Deep,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        uint FolderCount = 0, FileCount = 0;

                        for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 25)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(Index, 25);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in ReadOnlyItemList)
                                {
                                    if (Item.IsOfType(StorageItemTypes.Folder))
                                    {
                                        FolderCount++;
                                    }
                                    else
                                    {
                                        FileCount++;
                                    }

                                    if (CancelToken.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(FolderCount, FileCount);
                    }
                    else
                    {
                        return(0, 0);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{nameof(GetFolderAndFileNumAsync)} failed for uwp API");
                    return(0, 0);
                }
            }
        }