private async void Modified(string Path)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
            {
                try
                {
                    await Locker.WaitAsync();

                    try
                    {
                        if (CurrentLocation == System.IO.Path.GetDirectoryName(Path))
                        {
                            if (await FileSystemStorageItemBase.OpenAsync(Path) is FileSystemStorageItemBase ModifiedItem)
                            {
                                PathConfiguration Config = await SQLite.Current.GetPathConfigurationAsync(CurrentLocation);

                                if (CurrentCollection.FirstOrDefault((Item) => Item.Path.Equals(Path, StringComparison.OrdinalIgnoreCase)) is FileSystemStorageItemBase OldItem)
                                {
                                    if (ModifiedItem.GetType() == OldItem.GetType())
                                    {
                                        await OldItem.RefreshAsync();
                                    }
                                    else
                                    {
                                        CurrentCollection.Remove(OldItem);

                                        if (!SettingControl.IsDisplayProtectedSystemItems || !ModifiedItem.IsSystemItem)
                                        {
                                            if ((ModifiedItem is IHiddenStorageItem && SettingControl.IsDisplayHiddenItem) || ModifiedItem is not IHiddenStorageItem)
                                            {
                                                if (CurrentCollection.Any())
                                                {
                                                    int Index = SortCollectionGenerator.SearchInsertLocation(CurrentCollection, ModifiedItem, Config.SortTarget.GetValueOrDefault(), Config.SortDirection.GetValueOrDefault());

                                                    if (Index >= 0)
                                                    {
                                                        CurrentCollection.Insert(Index, ModifiedItem);
                                                    }
                                                    else
                                                    {
                                                        CurrentCollection.Add(ModifiedItem);
                                                    }
                                                }
                                                else
                                                {
                                                    CurrentCollection.Add(ModifiedItem);
                                                }
                                            }
                                        }
                                    }
                                }
                                else if (ModifiedItem is not IHiddenStorageItem)
                                {
                                    if (CurrentCollection.Any())
                                    {
                                        int Index = SortCollectionGenerator.SearchInsertLocation(CurrentCollection, ModifiedItem, Config.SortTarget.GetValueOrDefault(), Config.SortDirection.GetValueOrDefault());

                                        if (Index >= 0)
                                        {
                                            CurrentCollection.Insert(Index, ModifiedItem);
                                        }
                                        else
                                        {
                                            CurrentCollection.Add(ModifiedItem);
                                        }
                                    }
                                    else
                                    {
                                        CurrentCollection.Add(ModifiedItem);
                                    }
                                }
                            }
                        }
                    }
                    finally
                    {
                        Locker.Release();
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{ nameof(StorageAreaWatcher)}: Modify item in collection failed");
                }
            });
        private static async Task CreateTarGzipAsync(IEnumerable <FileSystemStorageItemBase> SourceItemGroup, string NewZipPath, CompressionLevel Level, ProgressChangedEventHandler ProgressHandler = null)
        {
            if (Level == CompressionLevel.Undefine)
            {
                throw new ArgumentException("Undefine is not allowed in this function", nameof(Level));
            }

            if (await FileSystemStorageItemBase.CreateAsync(NewZipPath, StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile)
            {
                ulong TotalSize       = 0;
                ulong CurrentPosition = 0;

                foreach (FileSystemStorageItemBase StorageItem in SourceItemGroup)
                {
                    switch (StorageItem)
                    {
                    case FileSystemStorageFile File:
                    {
                        TotalSize += File.SizeRaw;
                        break;
                    }

                    case FileSystemStorageFolder Folder:
                    {
                        TotalSize += await Folder.GetFolderSizeAsync().ConfigureAwait(false);

                        break;
                    }
                    }
                }

                if (TotalSize > 0)
                {
                    using (FileStream NewFileStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Exclusive).ConfigureAwait(false))
                        using (GZipOutputStream OutputGzipStream = new GZipOutputStream(NewFileStream))
                            using (TarOutputStream OutputTarStream = new TarOutputStream(OutputGzipStream, EncodingSetting))
                            {
                                OutputGzipStream.SetLevel((int)Level);
                                OutputGzipStream.IsStreamOwner = false;
                                OutputTarStream.IsStreamOwner  = false;

                                foreach (FileSystemStorageItemBase StorageItem in SourceItemGroup)
                                {
                                    switch (StorageItem)
                                    {
                                    case FileSystemStorageFile File:
                                    {
                                        using (FileStream FileStream = await File.GetFileStreamFromFileAsync(AccessMode.Read).ConfigureAwait(false))
                                        {
                                            TarEntry NewEntry = TarEntry.CreateTarEntry(File.Name);
                                            NewEntry.ModTime = DateTime.Now;
                                            NewEntry.Size    = FileStream.Length;

                                            OutputTarStream.PutNextEntry(NewEntry);

                                            await FileStream.CopyToAsync(OutputTarStream, ProgressHandler : (s, e) =>
                                                {
                                                    ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * File.SizeRaw)) * 100d / TotalSize), null));
                                                }).ConfigureAwait(false);
                                        }

                                        OutputTarStream.CloseEntry();

                                        CurrentPosition += File.SizeRaw;
                                        ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null));

                                        break;
                                    }

                                    case FileSystemStorageFolder Folder:
                                    {
                                        ulong InnerFolderSize = 0;

                                        await TarFolderCore(Folder, OutputTarStream, Folder.Name, (ByteRead) =>
                                            {
                                                InnerFolderSize = ByteRead;
                                                ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + ByteRead) * 100d / TotalSize), null));
                                            }).ConfigureAwait(false);

                                        CurrentPosition += InnerFolderSize;
                                        ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null));

                                        break;
                                    }
                                    }
                                }

                                await OutputTarStream.FlushAsync().ConfigureAwait(false);
                            }
                }
            }
            else
            {
                throw new UnauthorizedAccessException();
            }
        }
Example #3
0
        public static async Task ExtractTarAsync(FileSystemStorageFolder NewFolder, FileSystemStorageFile File, ProgressChangedEventHandler ProgressHandler = null)
        {
            using (FileStream BaseStream = await File.GetFileStreamFromFileAsync(AccessMode.Exclusive).ConfigureAwait(false))
                using (TarInputStream InputTarStream = new TarInputStream(BaseStream, Encoding.UTF8))
                {
                    BaseStream.Seek(0, SeekOrigin.Begin);

                    InputTarStream.IsStreamOwner = false;

                    long CurrentPosition = 0;

                    while (InputTarStream.GetNextEntry() is TarEntry Entry)
                    {
                        if (Entry.Name.Contains("/"))
                        {
                            string[] SplitFolderPath = Entry.Name.Split('/', StringSplitOptions.RemoveEmptyEntries);

                            string TempFolderPath = NewFolder.Path;

                            for (int i = 0; i < SplitFolderPath.Length - 1; i++)
                            {
                                if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(TempFolderPath, SplitFolderPath[i]), StorageItemTypes.Folder, CreateOption.OpenIfExist).ConfigureAwait(false) is FileSystemStorageFolder NextFolder)
                                {
                                    TempFolderPath = NextFolder.Path;
                                }
                                else
                                {
                                    throw new UnauthorizedAccessException("Could not create directory");
                                }
                            }

                            if (Entry.Name.Last() == '/')
                            {
                                if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(TempFolderPath, SplitFolderPath.Last()), StorageItemTypes.Folder, CreateOption.OpenIfExist).ConfigureAwait(false) == null)
                                {
                                    throw new UnauthorizedAccessException("Could not create directory");
                                }
                            }
                            else
                            {
                                if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(TempFolderPath, SplitFolderPath.Last()), StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile)
                                {
                                    using (FileStream NewFileStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Write).ConfigureAwait(false))
                                    {
                                        if (Entry.Size > 0)
                                        {
                                            await InputTarStream.CopyToAsync(NewFileStream, (s, e) =>
                                            {
                                                ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToInt64(e.ProgressPercentage / 100d * Entry.Size)) * 100d / BaseStream.Length), null));
                                            }).ConfigureAwait(false);
                                        }
                                        else
                                        {
                                            await InputTarStream.CopyToAsync(NewFileStream).ConfigureAwait(false);
                                        }
                                    }
                                }
                                else
                                {
                                    throw new UnauthorizedAccessException();
                                }
                            }
                        }
                        else
                        {
                            if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(NewFolder.Path, Entry.Name), StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile)
                            {
                                using (FileStream NewFileStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Write).ConfigureAwait(false))
                                {
                                    if (Entry.Size > 0)
                                    {
                                        await InputTarStream.CopyToAsync(NewFileStream, (s, e) =>
                                        {
                                            ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToInt64(e.ProgressPercentage / 100d * Entry.Size)) * 100d / BaseStream.Length), null));
                                        }).ConfigureAwait(false);
                                    }
                                    else
                                    {
                                        await InputTarStream.CopyToAsync(NewFileStream).ConfigureAwait(false);
                                    }
                                }
                            }
                            else
                            {
                                throw new UnauthorizedAccessException();
                            }
                        }

                        ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition = BaseStream.Position) * 100d / BaseStream.Length), null));
                    }
                }
        }
Example #4
0
        /// <summary>
        /// 执行ZIP文件创建功能
        /// </summary>
        /// <param name="SourceItemGroup">待压缩文件</param>
        /// <param name="NewZipPath">生成的Zip文件名</param>
        /// <param name="ZipLevel">压缩等级</param>
        /// <param name="ProgressHandler">进度通知</param>
        /// <returns>无</returns>
        public static async Task CreateZipAsync(IEnumerable <FileSystemStorageItemBase> SourceItemGroup, string NewZipPath, int ZipLevel, ProgressChangedEventHandler ProgressHandler = null)
        {
            if (await FileSystemStorageItemBase.CreateAsync(NewZipPath, StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile)
            {
                ulong TotalSize       = 0;
                ulong CurrentPosition = 0;

                using (FileStream NewFileStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Exclusive).ConfigureAwait(false))
                    using (ZipOutputStream OutputStream = new ZipOutputStream(NewFileStream))
                    {
                        OutputStream.SetLevel(ZipLevel);
                        OutputStream.UseZip64      = UseZip64.Dynamic;
                        OutputStream.IsStreamOwner = false;

                        foreach (FileSystemStorageItemBase StorageItem in SourceItemGroup)
                        {
                            switch (StorageItem)
                            {
                            case FileSystemStorageFile File:
                            {
                                TotalSize += File.SizeRaw;
                                break;
                            }

                            case FileSystemStorageFolder Folder:
                            {
                                TotalSize += await Folder.GetFolderSizeAsync().ConfigureAwait(false);

                                break;
                            }
                            }
                        }

                        foreach (FileSystemStorageItemBase StorageItem in SourceItemGroup)
                        {
                            switch (StorageItem)
                            {
                            case FileSystemStorageFile File:
                            {
                                using (FileStream FileStream = await File.GetFileStreamFromFileAsync(AccessMode.Read).ConfigureAwait(false))
                                {
                                    ZipEntry NewEntry = new ZipEntry(File.Name)
                                    {
                                        DateTime          = DateTime.Now,
                                        CompressionMethod = CompressionMethod.Deflated,
                                        Size = FileStream.Length
                                    };

                                    OutputStream.PutNextEntry(NewEntry);

                                    await FileStream.CopyToAsync(OutputStream, (s, e) =>
                                        {
                                            ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * File.SizeRaw)) * 100d / TotalSize), null));
                                        }).ConfigureAwait(false);
                                }

                                if (TotalSize > 0)
                                {
                                    CurrentPosition += File.SizeRaw;
                                    ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null));
                                }

                                break;
                            }

                            case FileSystemStorageFolder Folder:
                            {
                                ulong InnerFolderSize = await Folder.GetFolderSizeAsync().ConfigureAwait(false);

                                await ZipFolderCore(Folder, OutputStream, Folder.Name, (s, e) =>
                                    {
                                        if (TotalSize > 0)
                                        {
                                            ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * InnerFolderSize)) * 100d / TotalSize), null));
                                        }
                                    }).ConfigureAwait(false);

                                if (TotalSize > 0)
                                {
                                    CurrentPosition += InnerFolderSize;
                                    ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null));
                                }

                                break;
                            }
                            }
                        }

                        await OutputStream.FlushAsync().ConfigureAwait(false);
                    }
            }
            else
            {
                throw new UnauthorizedAccessException();
            }
        }
        /// <summary>
        /// 启动WIFI连接侦听器
        /// </summary>
        public async Task StartToListenRequest()
        {
            if (IsListeningThreadWorking)
            {
                return;
            }

            if (IsDisposed)
            {
                throw new ObjectDisposedException("This Object has been disposed");
            }

            IsListeningThreadWorking = true;

            try
            {
                Listener.Start();

                while (true)
                {
                    HttpListenerContext Context = await Listener.GetContextAsync().ConfigureAwait(false);

                    _ = Task.Factory.StartNew(async(Para) =>
                    {
                        try
                        {
                            HttpListenerContext HttpContext = Para as HttpListenerContext;

                            if (HttpContext.Request.Url.LocalPath.Substring(1) == FilePathMap.Key)
                            {
                                if (await FileSystemStorageItemBase.OpenAsync(FilePathMap.Value, ItemFilters.File).ConfigureAwait(true) is FileSystemStorageItemBase ShareFile)
                                {
                                    using (FileStream Stream = ShareFile.GetFileStreamFromFile(AccessMode.Read))
                                    {
                                        try
                                        {
                                            Context.Response.AddHeader("Pragma", "No-cache");
                                            Context.Response.AddHeader("Cache-Control", "No-cache");
                                            Context.Response.AddHeader("Content-Disposition", $"Attachment;filename={Uri.EscapeDataString(ShareFile.Name)}");
                                            Context.Response.ContentLength64 = Stream.Length;
                                            Context.Response.ContentType     = "application/octet-stream";

                                            Stream.CopyTo(Context.Response.OutputStream);
                                        }
                                        catch (HttpListenerException ex)
                                        {
                                            LogTracer.Log(ex);
                                        }
                                        finally
                                        {
                                            Context.Response.Close();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                string ErrorMessage                = $"<html><head><title>Error 404 Bad Request</title></head><body><p style=\"font-size:50px\">HTTP ERROR 404</p><p style=\"font-size:40px\">{Globalization.GetString("WIFIShare_Error_Web_Content")}</p></body></html>";
                                Context.Response.StatusCode        = 404;
                                Context.Response.StatusDescription = "Bad Request";
                                Context.Response.ContentType       = "text/html";
                                Context.Response.ContentEncoding   = Encoding.UTF8;
                                using (StreamWriter Writer = new StreamWriter(Context.Response.OutputStream, Encoding.UTF8))
                                {
                                    Writer.Write(ErrorMessage);
                                }
                                Context.Response.Close();
                            }
                        }
                        catch (Exception e)
                        {
                            LogTracer.Log(e);
                            ThreadExitedUnexpectly?.Invoke(this, e);
                        }
                    }, Context, Cancellation.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
                }
            }
            catch (ObjectDisposedException)
            {
                IsListeningThreadWorking = false;
            }
            catch (Exception e)
            {
                IsListeningThreadWorking = false;
                ThreadExitedUnexpectly?.Invoke(this, e);
            }
            finally
            {
                Cancellation?.Dispose();
                Cancellation = null;
            }
        }
Example #6
0
            public static async Task <DriveChangeDeferredEventArgs> CreateAsync(DriveDataBase Data)
            {
                FileSystemStorageItemBase Item = await FileSystemStorageItemBase.CreateFromStorageItemAsync(Data.DriveFolder);

                return(new DriveChangeDeferredEventArgs(Item as FileSystemStorageFolder));
            }
        public static async IAsyncEnumerable <string[]> GetAllPathAsync(StartupMode Mode)
        {
            if (Mode == StartupMode.CreateNewTab)
            {
                yield break;
            }

            switch (Mode)
            {
            case StartupMode.CreateNewTab:
            {
                yield break;
            }

            case StartupMode.SpecificTab:
            {
                if (ApplicationData.Current.LocalSettings.Values["StartupWithSpecificPath"] is string RawData)
                {
                    if (string.IsNullOrWhiteSpace(RawData))
                    {
                        yield break;
                    }

                    foreach (string Path in JsonSerializer.Deserialize <List <string> >(RawData))
                    {
                        if (await FileSystemStorageItemBase.CheckExistAsync(Path).ConfigureAwait(false))
                        {
                            yield return(new string[] { Path });
                        }
                    }
                }
                else
                {
                    yield break;
                }

                break;
            }

            case StartupMode.LastOpenedTab:
            {
                if (ApplicationData.Current.LocalSettings.Values["StartupWithLastOpenedPath"] is string RawData)
                {
                    if (string.IsNullOrWhiteSpace(RawData))
                    {
                        yield break;
                    }

                    foreach (string[] PathList in JsonSerializer.Deserialize <List <string[]> >(RawData).Where((Path) => Path.Length > 0))
                    {
                        List <string> ValidPathList = new List <string>(PathList.Length);

                        foreach (string ValidPath in PathList)
                        {
                            if (await FileSystemStorageItemBase.CheckExistAsync(ValidPath).ConfigureAwait(false))
                            {
                                ValidPathList.Add(ValidPath);
                            }
                        }

                        yield return(ValidPathList.ToArray());
                    }
                }
                else
                {
                    yield break;
                }

                break;
            }
            }
        }
Example #8
0
        public static async Task <FileSystemStorageFile> GetBingPictureAsync()
        {
            string Path = await GetDailyPhotoPath().ConfigureAwait(false);

            if (await FileSystemStorageItemBase.OpenAsync(System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, "BingDailyPicture.jpg")) is FileSystemStorageFile ExistFile)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(Path))
                    {
                        return(ExistFile);
                    }

                    if (await CheckIfNeedToUpdate())
                    {
                        if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.TemporaryFolder.Path, $"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg"), StorageItemTypes.File, CreateOption.GenerateUniqueName) is FileSystemStorageFile TempFile)
                        {
                            using (FileStream TempFileStream = await TempFile.GetFileStreamFromFileAsync(AccessMode.ReadWrite))
                            {
                                HttpWebRequest Request = WebRequest.CreateHttp(new Uri($"https://www.bing.com{Path}"));
                                Request.Timeout          = 10000;
                                Request.ReadWriteTimeout = 10000;

                                using (WebResponse Response = await Request.GetResponseAsync())
                                    using (Stream ResponseStream = Response.GetResponseStream())
                                    {
                                        await ResponseStream.CopyToAsync(TempFileStream);
                                    }

                                using (Stream FileStream = await ExistFile.GetFileStreamFromFileAsync(AccessMode.Read))
                                    using (MD5 MD5Alg1 = MD5.Create())
                                        using (MD5 MD5Alg2 = MD5.Create())
                                        {
                                            Task <string> CalTask1 = MD5Alg1.GetHashAsync(FileStream);
                                            Task <string> CalTask2 = MD5Alg2.GetHashAsync(TempFileStream);

                                            string[] ResultArray = await Task.WhenAll(CalTask1, CalTask2);

                                            if (ResultArray[0] == ResultArray[1])
                                            {
                                                return(ExistFile);
                                            }
                                        }

                                TempFileStream.Seek(0, SeekOrigin.Begin);

                                using (StorageStreamTransaction Transaction = await ExistFile.GetTransactionStreamFromFileAsync())
                                {
                                    await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite());

                                    await Transaction.CommitAsync();
                                }
                            }
                        }
                        else
                        {
                            LogTracer.Log($"Could not create temp file as needed in {nameof(GetBingPictureAsync)}");
                        }

                        return(ExistFile);
                    }
                    else
                    {
                        return(ExistFile);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An error was threw in {nameof(GetBingPictureAsync)}");
                    return(ExistFile);
                }
            }
            else
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(Path))
                    {
                        return(null);
                    }

                    if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.TemporaryFolder.Path, $"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg"), StorageItemTypes.File, CreateOption.GenerateUniqueName) is FileSystemStorageFile TempFile)
                    {
                        using (Stream TempFileStream = await TempFile.GetFileStreamFromFileAsync(AccessMode.ReadWrite))
                        {
                            HttpWebRequest Request = WebRequest.CreateHttp(new Uri($"https://www.bing.com{Path}"));
                            Request.Timeout          = 10000;
                            Request.ReadWriteTimeout = 10000;

                            using (WebResponse Response = await Request.GetResponseAsync())
                                using (Stream ResponseStream = Response.GetResponseStream())
                                {
                                    await ResponseStream.CopyToAsync(TempFileStream);
                                }

                            if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, "BingDailyPicture.jpg"), StorageItemTypes.File, CreateOption.ReplaceExisting) is FileSystemStorageFile BingDailyPictureFile)
                            {
                                using (StorageStreamTransaction Transaction = await BingDailyPictureFile.GetTransactionStreamFromFileAsync())
                                {
                                    TempFileStream.Seek(0, SeekOrigin.Begin);
                                    await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite());

                                    await Transaction.CommitAsync();
                                }

                                return(BingDailyPictureFile);
                            }
                            else
                            {
                                LogTracer.Log($"Could not create BingPicture file as needed in {nameof(GetBingPictureAsync)}");
                                return(null);
                            }
                        }
                    }
                    else
                    {
                        LogTracer.Log($"Could not create temp file as needed in {nameof(GetBingPictureAsync)}");
                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An error was threw in {nameof(GetBingPictureAsync)}");
                    return(null);
                }
            }
        }
Example #9
0
        /// <summary>
        /// 执行ZIP解压功能
        /// </summary>
        /// <param name="File">ZIP文件</param>
        /// <returns>无</returns>
        public static async Task ExtractZipAsync(FileSystemStorageFolder NewFolder, FileSystemStorageFile File, ProgressChangedEventHandler ProgressHandler = null)
        {
            ZipStrings.CodePage = EncodingSetting.CodePage;

            using (FileStream BaseStream = await File.GetFileStreamFromFileAsync(AccessMode.Exclusive).ConfigureAwait(false))
                using (ZipInputStream InputZipStream = new ZipInputStream(BaseStream))
                {
                    BaseStream.Seek(0, SeekOrigin.Begin);

                    InputZipStream.IsStreamOwner = false;

                    long CurrentPosition = 0;

                    while (InputZipStream.GetNextEntry() is ZipEntry Entry)
                    {
                        if (!InputZipStream.CanDecompressEntry || Entry.IsCrypted)
                        {
                            throw new NotImplementedException();
                        }

                        if (Entry.Name.Contains("/"))
                        {
                            string[] SplitFolderPath = Entry.Name.Split('/', StringSplitOptions.RemoveEmptyEntries);

                            string TempFolderPath = NewFolder.Path;

                            for (int i = 0; i < SplitFolderPath.Length - 1; i++)
                            {
                                if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(TempFolderPath, SplitFolderPath[i]), StorageItemTypes.Folder, CreateOption.OpenIfExist).ConfigureAwait(false) is FileSystemStorageFolder NextFolder)
                                {
                                    TempFolderPath = NextFolder.Path;
                                }
                                else
                                {
                                    throw new UnauthorizedAccessException("Could not create directory");
                                }
                            }

                            if (Entry.Name.Last() == '/')
                            {
                                if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(TempFolderPath, SplitFolderPath.Last()), StorageItemTypes.Folder, CreateOption.OpenIfExist).ConfigureAwait(false) == null)
                                {
                                    throw new UnauthorizedAccessException("Could not create directory");
                                }
                            }
                            else
                            {
                                if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(TempFolderPath, SplitFolderPath.Last()), StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile)
                                {
                                    using (FileStream NewFileStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Write).ConfigureAwait(false))
                                    {
                                        //For some files in Zip, CompressedSize or Size might less than zero, then we could not get progress by reading ZipInputStream.Length
                                        if (Entry.CompressedSize > 0 && Entry.Size > 0)
                                        {
                                            await InputZipStream.CopyToAsync(NewFileStream, (s, e) =>
                                            {
                                                ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToInt64(e.ProgressPercentage / 100d * Entry.CompressedSize)) * 100d / BaseStream.Length), null));
                                            }).ConfigureAwait(false);
                                        }
                                        else
                                        {
                                            await InputZipStream.CopyToAsync(NewFileStream).ConfigureAwait(false);
                                        }
                                    }
                                }
                                else
                                {
                                    throw new UnauthorizedAccessException();
                                }
                            }
                        }
                        else
                        {
                            if (await FileSystemStorageItemBase.CreateAsync(Path.Combine(NewFolder.Path, Entry.Name), StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile)
                            {
                                using (FileStream NewFileStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Write).ConfigureAwait(false))
                                {
                                    //For some files in Zip, CompressedSize or Size might less than zero, then we could not get progress by reading ZipInputStream.Length
                                    if (Entry.CompressedSize > 0 && Entry.Size > 0)
                                    {
                                        await InputZipStream.CopyToAsync(NewFileStream, (s, e) =>
                                        {
                                            ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToInt64(e.ProgressPercentage / 100d * Entry.CompressedSize)) * 100d / BaseStream.Length), null));
                                        }).ConfigureAwait(true);
                                    }
                                    else
                                    {
                                        await InputZipStream.CopyToAsync(NewFileStream).ConfigureAwait(false);
                                    }
                                }
                            }
                            else
                            {
                                throw new UnauthorizedAccessException();
                            }
                        }

                        ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition = BaseStream.Position) * 100d / BaseStream.Length), null));
                    }
                }
        }