Beispiel #1
0
        internal ArchiveEntry(ZipStorer zip, ZipStorer.ZipFileEntry entry)
        {
            if (entry.FilenameInZip.EndsWith(".json", System.StringComparison.OrdinalIgnoreCase))
            {
                this.Type = EntryType.Metadata;
            }
            else if (entry.FilenameInZip.EndsWith(".jpg", System.StringComparison.OrdinalIgnoreCase))
            {
                this.Type = EntryType.Image;
            }
            else if (entry.FilenameInZip.EndsWith(".png", System.StringComparison.OrdinalIgnoreCase))
            {
                this.Type = EntryType.Image;
            }
            else if (entry.FilenameInZip.EndsWith(".bmp", System.StringComparison.OrdinalIgnoreCase))
            {
                this.Type = EntryType.Image;
            }
            else if (entry.FilenameInZip.EndsWith(".jpeg", System.StringComparison.OrdinalIgnoreCase))
            {
                this.Type = EntryType.Image;
            }
            else
            {
                this.Type = EntryType.None;
            }

            this.Filename   = entry.FilenameInZip;
            this.CRC        = entry.Crc32;
            this.Filesize   = entry.FileSize;
            this.innerentry = entry;
            this.innterzip  = zip;
        }
Beispiel #2
0
 public PakkedFile(string name, int index, ZipStorer.ZipFileEntry entry)
 {
     Name     = name;
     IsPakked = true;
     PakIndex = index;
     Entry    = entry;
 }
Beispiel #3
0
        /////////////////////////////////////////////////////////////////////////////
/////////// Функции обработки сообщений /////////////////////////////////////
        /// <summary>
        /// обработка сообщения FILE
        /// </summary>
        /// <param name="iU"> номер пользователя </param>
        /// <param name="data"> указатель на полученные от клиента данные </param>
        private void AddFile(byte[] data)
        {
            int    curPos   = 5 * 2;                     //'FILE '     - текущая позиция для чтения в полученном сообщении
            string nameFile = GetPasString(data, 5 * 2); //имя файла

            curPos += nameFile.Length * 2 + 1;
            int sizeFile = ToInt(data, curPos);             //размер файла

            curPos += 4;

            if (Access.AddFile(nameFile, sizeFile, Login))
            {
                try
                {
                    byte[] bfsize = new byte[4];
                    CryRd.Read(bfsize, 0, 4);
                    uint allFileSize = (uint)ToInt(bfsize);

                    ZipStorer zip;

                    zip            = ZipStorer.Create(nameFile + ".zip", "");
                    zip.EncodeUTF8 = true;

                    ZipStorer.ZipFileEntry zfe = zip.AS_Create(ZipStorer.Compression.Deflate, nameFile, DateTime.Now, "");
                    Stream zipstr = zip.AS_GetStream(zfe, 0);
                    uint   rds    = zip.AS_Write(zfe, zipstr, CryRd, allFileSize);
                    zip.AS_Close(zfe, zipstr, rds);
                    zip.Close();
                }
                catch (Exception e)
                {
                    Access.DeleteFile(nameFile);
                    Console.Write(e.Message);
                    Console.WriteLine("{0}: ошибка добавления файла {1}", Login, nameFile);
                    ConLog.Write(e.Message);
                    ConLog.WriteLine("{0}: ошибка добавления файла {1}", Login, nameFile);
                }

                Console.WriteLine("{0}: добавлен файл {1}", Login, nameFile);
                ConLog.WriteLine("{0}: добавлен файл {1}", Login, nameFile);
                SendResponse(CryWr, "FILE_OK");
            }
            else
            {
                Console.WriteLine("{0}: ошибка добавления файла {1}", Login, nameFile);
                ConLog.WriteLine("{0}: ошибка добавления файла {1}", Login, nameFile);
                SendResponse(CryWr, "FILE_ERR");
            }
        }
Beispiel #4
0
        private static BitmapImage GetIconFrom(string pathApk, string pathIcon)
        {
            try
            {
                using (var stream = new MemoryStream())
                    using (var zip = ZipStorer.Open(pathApk, FileAccess.Read))
                    {
                        ZipStorer.ZipFileEntry fileEntry = null;
                        if (pathIcon.EndsWith(".xml"))
                        {
                            // try finding png icon from xml path
                            var icon = Path.GetFileNameWithoutExtension(pathIcon) + ".png";
                            fileEntry = zip.ReadCentralDir().Where(f => f.FilenameInZip.EndsWith(icon) && f.FilenameInZip.Contains("hdpi")).LastOrDefault();
                        }
                        else
                        {
                            fileEntry = zip.ReadCentralDir().Where(f => f.FilenameInZip.Equals(pathIcon)).FirstOrDefault();
                        }

                        if (fileEntry != null)
                        {
                            zip.ExtractFile(fileEntry, stream);
                        }
                        else
                        {
                            throw new Exception("there is no png icon in the apk");
                        }

                        var bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.StreamSource = stream;
                        bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                        bitmap.EndInit();
                        bitmap.Freeze();

                        return(bitmap);
                    }
            }
            catch (Exception e)
            {
                Debug.Print("Apk.GetIcon: {0}", e.Message);
                return(App.GetPlaystoreImageFromResources());
            }
        }
Beispiel #5
0
        public void Test_Common()
        {
            Assert.Throws(typeof(ArgumentNullException), () => { ZipStorer.Open("", FileAccess.Read); });

            string fileName = TestStubs.GetTempFilePath("test.zip");

            using (ZipStorer zip = ZipStorer.Create(fileName, "test")) {
                using (MemoryStream csvStream = new MemoryStream(Encoding.ASCII.GetBytes(TestStubs.CSVData))) {
                    zip.AddStream(ZipStorer.Compression.Deflate, "csv_file.csv", csvStream, DateTime.Now, "");
                }

                Assert.Throws(typeof(InvalidOperationException), () => { zip.ReadCentralDir(); });

                ZipStorer xzip = null;
                Assert.Throws(typeof(ArgumentNullException), () => { xzip = ZipStorer.RemoveEntries(xzip, null); });
                Assert.Throws(typeof(ArgumentNullException), () => { xzip = ZipStorer.RemoveEntries(xzip, null); });
            }

            using (ZipStorer zip = ZipStorer.Open(fileName, FileAccess.Read)) {
                Assert.Throws(typeof(ArgumentNullException), () => { zip.FindFile(null); });

                ZipStorer.ZipFileEntry entry = zip.FindFile("invalid");
                Assert.IsNull(entry);

                entry = zip.FindFile("csv_file.csv");
                Assert.IsNotNull(entry);

                using (MemoryStream csvStream = new MemoryStream()) {
                    Assert.Throws(typeof(ArgumentNullException), () => { zip.ExtractStream(entry, null); });

                    zip.ExtractStream(entry, csvStream);

                    csvStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(csvStream, Encoding.ASCII)) {
                        string text = reader.ReadToEnd();
                        Assert.AreEqual(TestStubs.CSVData, text);
                    }
                }
            }
        }
Beispiel #6
0
        private void FormMain_Shown(object sender, EventArgs e)
        {
            _logBuilder.AppendLine(DateTime.Now.ToString("F"));
            _logBuilder.AppendLine();
            _logBuilder.AppendLine("ZipExtractor started with following command line arguments.");

            string[] args = Environment.GetCommandLineArgs();
            //string[] args = new string[] { @"C:\Users\tangwy\AppData\Local\Temp\UpdateServer.zip",@"C:\Users\tangwy\Downloads\AutoUpdater.NET-master\AutoUpdaterTestWPF\bin\Debug" ,@"C:\Users\tangwy\Downloads\AutoUpdater.NET-master\AutoUpdaterTestWPF\bin\Debug\AutoUpdaterTestWPF.exe" };
            for (var index = 0; index < args.Length; index++)
            {
                var arg = args[index];
                _logBuilder.AppendLine($"[{index}] {arg}");
            }

            _logBuilder.AppendLine();

            if (args.Length >= 4)
            {
                string executablePath = args[3];

                // Extract all the files.
                _backgroundWorker = new BackgroundWorker
                {
                    WorkerReportsProgress      = true,
                    WorkerSupportsCancellation = true
                };

                _backgroundWorker.DoWork += (o, eventArgs) =>
                {
                    foreach (var process in Process.GetProcesses())
                    {
                        try
                        {
                            if (process.MainModule.FileName.Equals(executablePath))
                            {
                                _logBuilder.AppendLine("Waiting for application process to Exit...");

                                _backgroundWorker.ReportProgress(0, "Waiting for application to Exit...");
                                process.WaitForExit();
                            }
                        }
                        catch (Exception exception)
                        {
                            Debug.WriteLine(exception.Message);
                        }
                    }

                    _logBuilder.AppendLine("BackgroundWorker started successfully.");

                    var path = args[2];

                    // Open an existing zip file for reading.
                    ZipStorer zip = ZipStorer.Open(args[1], FileAccess.Read);

                    // Read the central directory collection.
                    List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                    _logBuilder.AppendLine($"Found total of {dir.Count} files and folders inside the zip file.");

                    for (var index = 0; index < dir.Count; index++)
                    {
                        if (_backgroundWorker.CancellationPending)
                        {
                            eventArgs.Cancel = true;
                            zip.Close();
                            return;
                        }

                        ZipStorer.ZipFileEntry entry = dir[index];
                        zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip));
                        string currentFile = string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip);
                        int    progress    = (index + 1) * 100 / dir.Count;
                        _backgroundWorker.ReportProgress(progress, currentFile);

                        _logBuilder.AppendLine($"{currentFile} [{progress}%]");
                    }

                    zip.Close();
                };

                _backgroundWorker.ProgressChanged += (o, eventArgs) =>
                {
                    progressBar.Value     = eventArgs.ProgressPercentage;
                    labelInformation.Text = eventArgs.UserState.ToString();
                };

                _backgroundWorker.RunWorkerCompleted += (o, eventArgs) =>
                {
                    try
                    {
                        if (eventArgs.Error != null)
                        {
                            throw eventArgs.Error;
                        }

                        if (!eventArgs.Cancelled)
                        {
                            labelInformation.Text = @"Finished";
                            try
                            {
                                ProcessStartInfo processStartInfo = new ProcessStartInfo(executablePath);
                                if (args.Length > 4)
                                {
                                    processStartInfo.Arguments = args[4];
                                }

                                Process.Start(processStartInfo);

                                _logBuilder.AppendLine("Successfully launched the updated application.");
                            }
                            catch (Win32Exception exception)
                            {
                                if (exception.NativeErrorCode != 1223)
                                {
                                    throw;
                                }
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        _logBuilder.AppendLine();
                        _logBuilder.AppendLine(exception.ToString());

                        MessageBox.Show(exception.Message, exception.GetType().ToString(),
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        _logBuilder.AppendLine();
                        Application.Exit();
                    }
                };

                _backgroundWorker.RunWorkerAsync();
            }
        }
Beispiel #7
0
        private void FormMain_Shown(object sender, EventArgs e)
        {
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length.Equals(3))
            {
                foreach (var process in Process.GetProcesses())
                {
                    try
                    {
                        if (process.MainModule.FileName.Equals(args[2]))
                        {
                            labelInformation.Text = @"Waiting for application to Exit...";
                            process.WaitForExit();
                        }
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception.Message);
                    }
                }

                // Extract all the files.
                _backgroundWorker = new BackgroundWorker
                {
                    WorkerReportsProgress      = true,
                    WorkerSupportsCancellation = true
                };

                _backgroundWorker.DoWork += (o, eventArgs) =>
                {
                    var path = Path.GetDirectoryName(args[2]);

                    // Open an existing zip file for reading.
                    ZipStorer zip = ZipStorer.Open(args[1], FileAccess.Read);

                    // Read the central directory collection.
                    List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                    for (var index = 0; index < dir.Count; index++)
                    {
                        if (_backgroundWorker.CancellationPending)
                        {
                            eventArgs.Cancel = true;
                            zip.Close();
                            return;
                        }
                        ZipStorer.ZipFileEntry entry = dir[index];
                        zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip));
                        _backgroundWorker.ReportProgress((index + 1) * 100 / dir.Count, string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip));
                    }

                    zip.Close();
                };

                _backgroundWorker.ProgressChanged += (o, eventArgs) =>
                {
                    progressBar.Value     = eventArgs.ProgressPercentage;
                    labelInformation.Text = eventArgs.UserState.ToString();
                };

                _backgroundWorker.RunWorkerCompleted += (o, eventArgs) =>
                {
                    if (!eventArgs.Cancelled)
                    {
                        labelInformation.Text = @"Finished";
                        try
                        {
                            Process.Start(args[2]);
                        }
                        catch (Win32Exception exception)
                        {
                            if (exception.NativeErrorCode != 1223)
                            {
                                throw;
                            }
                        }
                        Application.Exit();
                    }
                };
                _backgroundWorker.RunWorkerAsync();
            }
        }
Beispiel #8
0
 public ZipStorerZipArchiveEntry(ZipStorer.ZipFileEntry entry)
 {
     this.BaseEntry = entry;
 }
Beispiel #9
0
        static void Main(string[] args)
        {
            BackgroundWorker _backgroundWorker;

            if (args.Length >= 3)
            {
                foreach (var process in Process.GetProcesses())
                {
                    try
                    {
                        if (process.MainModule.FileName.Equals(args[2]))
                        {
                            Console.WriteLine(@"Waiting for application to Exit...");
                            process.WaitForExit();
                        }
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception.Message);
                    }
                }

                // Extract all the files.
                _backgroundWorker = new BackgroundWorker
                {
                    WorkerReportsProgress      = true,
                    WorkerSupportsCancellation = true
                };

                _backgroundWorker.DoWork += (o, eventArgs) =>
                {
                    var path = Path.GetDirectoryName(args[2]);

                    // Open an existing zip file for reading.
                    ZipStorer zip = ZipStorer.Open(args[1], FileAccess.Read);

                    // Read the central directory collection.
                    List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                    for (var index = 0; index < dir.Count; index++)
                    {
                        if (_backgroundWorker.CancellationPending)
                        {
                            eventArgs.Cancel = true;
                            zip.Close();
                            return;
                        }
                        ZipStorer.ZipFileEntry entry = dir[index];
                        zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip));
                        _backgroundWorker.ReportProgress((index + 1) * 100 / dir.Count, string.Format("Extracting {0}", entry.FilenameInZip));
                    }

                    zip.Close();
                };

                _backgroundWorker.ProgressChanged += (o, eventArgs) =>
                {
                    Console.WriteLine("{0} {1}", eventArgs.ProgressPercentage, eventArgs.UserState);
                };

                _backgroundWorker.RunWorkerCompleted += (o, eventArgs) =>
                {
                    if (!eventArgs.Cancelled)
                    {
                        Console.WriteLine(@"Finished");
                        try
                        {
                            ProcessStartInfo processStartInfo = new ProcessStartInfo(args[2]);
                            if (args.Length > 3)
                            {
                                processStartInfo.Arguments = args[3];
                            }
                            Process.Start(processStartInfo);
                        }
                        catch (Win32Exception exception)
                        {
                            if (exception.NativeErrorCode != 1223)
                            {
                                throw;
                            }
                        }
                        Environment.Exit(0);
                    }
                };
                _backgroundWorker.RunWorkerAsync();
            }
        }
Beispiel #10
0
 private void ExtractFile(ZipStorer zipStorer, ZipStorer.ZipFileEntry zipFileEntry, string writeToPath)
 {
     zipStorer.ExtractFile(zipFileEntry, writeToPath);
     WriteLineConsole(string.Format("Extacted : {0}", writeToPath));
 }
        private void FormMain_Shown(object sender, EventArgs e)
        {
            string[] args = Environment.GetCommandLineArgs();
            foreach (string s in args)
            {
                if (s.IndexOf("silent", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    this.Hide();
                    this.WindowState   = FormWindowState.Minimized;
                    this.Visible       = false;               // Hide form window.
                    this.ShowInTaskbar = false;               // Remove from taskbar.
                    this.Opacity       = 0;
                }
            }

            if (args.Length >= 3)
            {
                //          foreach (var process in Process.GetProcesses())
                //          {
                //              try
                //              {
                //                  if (process.MainModule.FileName.Equals(args[2]))
                //                  {
                //	WriteLogMessage( $"INFO: Waiting for application to Exit..." );
                //                      labelInformation.Text = @"Waiting for application to Exit...";
                //                      process.WaitForExit();
                //                  }
                //              }
                //              catch (Exception ex)
                //              {
                //WriteLogMessage( $"ERROR: {ex.Message} - {ex.InnerException?.Message} - {ex.StackTrace}" );
                //              }
                //          }

                // Extract all the files.
                _backgroundWorker = new BackgroundWorker
                {
                    WorkerReportsProgress      = true,
                    WorkerSupportsCancellation = true
                };

                _backgroundWorker.DoWork += (o, eventArgs) =>
                {
                    try {
                        var path = Path.GetDirectoryName(args[2]);

                        using (ZipStorer zip = ZipStorer.Open(args[1], FileAccess.Read)) {
                            // Read the central directory collection.
                            List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                            for (var index = 0; index < dir.Count; index++)
                            {
                                if (_backgroundWorker.CancellationPending)
                                {
                                    eventArgs.Cancel = true;
                                    zip.Close();
                                    return;
                                }

                                ZipStorer.ZipFileEntry entry = dir[index];
                                zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip));
                                _backgroundWorker.ReportProgress((index + 1) * 100 / dir.Count,
                                                                 string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip));
                            }

                            zip.Close();
                        }
                    } catch (Exception ex) {
                        WriteLogMessage($"ERROR: {ex.Message} - {ex.InnerException?.Message} - {ex.StackTrace}");
                        eventArgs.Cancel = true;
                    }
                };

                _backgroundWorker.ProgressChanged += (o, eventArgs) =>
                {
                    progressBar.Value     = eventArgs.ProgressPercentage;
                    labelInformation.Text = eventArgs.UserState.ToString();
                };

                _backgroundWorker.RunWorkerCompleted += (o, eventArgs) =>
                {
                    if (!eventArgs.Cancelled)
                    {
                        labelInformation.Text = @"Finished";
                        string arguments = (args.Length > 3) ? args[3] : null;
                        WriteLogMessage($"INFO: Finished. Run Application {args[2]} {arguments}");

                        try {
                            ProcessStartInfo processStartInfo = new ProcessStartInfo(args[2]);
                            if (arguments != null)
                            {
                                processStartInfo.Arguments = arguments;
                            }

                            WriteLogMessage($"INFO: Finished");
                            Process.Start(processStartInfo);
                        }
                        catch (Win32Exception ex)
                        {
                            if (ex.NativeErrorCode != 1223)
                            {
                                WriteLogMessage($"ERROR: {ex.Message} - {ex.InnerException?.Message} - {ex.StackTrace}");
                            }
                        }

                        Application.Exit();
                    }
                    else
                    {
                        WriteLogMessage($"INFO: Cancelled");
                    }
                };
                _backgroundWorker.RunWorkerAsync();
            }
        }
Beispiel #12
0
        private void FormMain_Shown(object sender, EventArgs e)
        {
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length >= 3)
            {
                //解压升级包的临时目录
                var tempDirectory = args[1];
                ///主程序完整路径
                var main_exeFullName = args[2];
                //检查是否需要重新启动
                var needRestart = "true".Equals(args[3], StringComparison.InvariantCultureIgnoreCase);
                if (needRestart)
                {
                    foreach (var process in Process.GetProcesses())
                    {
                        try
                        {
                            if (process.MainModule.FileName.Equals(main_exeFullName))
                            {
                                labelInformation.Text = @"等待主程序退出...";
                                process.WaitForExit();
                            }
                        }
                        catch (Exception exception)
                        {
                            Debug.WriteLine(exception.Message);
                        }
                    }
                }

                // Extract all the files.
                _backgroundWorker = new BackgroundWorker
                {
                    WorkerReportsProgress      = true,
                    WorkerSupportsCancellation = true
                };

                _backgroundWorker.DoWork += (o, eventArgs) =>
                {
                    try
                    {
                        labelInformation.Text = @"开始备份程序文件...";
                        var path = Path.GetDirectoryName(main_exeFullName);

                        #region 更新之前备份TechSVR的程序文件
                        var bakDirectory = Path.Combine(path, Constants.Bak_TechSvr + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒ffff"));
                        if (!Directory.Exists(bakDirectory))
                        {
                            Directory.CreateDirectory(bakDirectory);

                            foreach (var file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
                            {
                                if (!file.Contains(Constants.Bak_TechSvr))
                                {
                                    var destFile      = file.Replace(path, bakDirectory);
                                    var destDirectory = Path.GetDirectoryName(destFile);
                                    if (!Directory.Exists(destDirectory))
                                    {
                                        Directory.CreateDirectory(destDirectory);
                                    }
                                    File.Copy(file, destFile, true);
                                }
                            }
                        }
                        #endregion


                        var isContainDll = false;
                        labelInformation.Text = @"开始安装升级程序包...";
                        #region 解压升级包到主程序的安装目录
                        // Open an existing zip file for reading.
                        using (ZipStorer zip = ZipStorer.Open(tempDirectory, FileAccess.Read))
                        {
                            // Read the central directory collection.
                            List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                            for (var index = 0; index < dir.Count; index++)
                            {
                                if (_backgroundWorker.CancellationPending)
                                {
                                    eventArgs.Cancel = true;
                                    zip.Close();
                                    return;
                                }
                                ZipStorer.ZipFileEntry entry = dir[index];

                                var filename = Path.Combine(path, entry.FilenameInZip);
                                isContainDll = filename.EndsWith(".dll");
                                zip.ExtractFile(entry, filename);
                                _backgroundWorker.ReportProgress((index + 1) * 100 / dir.Count, string.Format(Resources.CurrentFileExtracting, entry.FilenameInZip));
                            }
                        }
                        #endregion

                        //如果升级的文件中包含DLL 且没有要求重启主程序,择触发自动升级事件,让程序重新加载插件数据
                        if (isContainDll && !needRestart)
                        {
                            autoUpdateHappenedEvent.Set();
                        }
                    }
                    catch (Exception ex)
                    {
                        labelInformation.Text = @"安装升级程序包出错...";
                        MessageBox.Show("安装出错," + ex.ToString());
                    }
                };

                _backgroundWorker.ProgressChanged += (o, eventArgs) =>
                {
                    progressBar.Value     = eventArgs.ProgressPercentage;
                    labelInformation.Text = eventArgs.UserState.ToString();
                };

                _backgroundWorker.RunWorkerCompleted += (o, eventArgs) =>
                {
                    if (!eventArgs.Cancelled)
                    {
                        labelInformation.Text = @"Finished";
                        try
                        {   //如果需要重新启动主程序,则由此开始启动程序
                            if (needRestart)
                            {
                                ProcessStartInfo processStartInfo = new ProcessStartInfo(main_exeFullName);
                                if (args.Length > 4)
                                {
                                    processStartInfo.Arguments = args[4];
                                }
                                Process.Start(processStartInfo);
                            }
                        }
                        catch (Win32Exception exception)
                        {
                            if (exception.NativeErrorCode != 1223)
                            {
                                throw;
                            }
                        }
                        Application.Exit();
                    }
                };
                _backgroundWorker.RunWorkerAsync();
            }
            labelInformation.Text = @"参数不正确...";
        }
Beispiel #13
0
 public bool IsExist(string fileName)
 {
     ZipStorer.ZipFileEntry entry = GetEntry(fileName);
     return(entry != null);
 }
Beispiel #14
0
        public gSheet Sheet = null;                                                                                             // This links to a data sheet if his stream implements a data sheet

        public gStream(OoXml doc, ZipStorer zip, ZipStorer.ZipFileEntry z)                                                      // This constructor is called when creating the stream from the source template
        {
            Document = doc;                                                                                                     // Save a reference to the document
            zfe      = z;                                                                                                       // Store the ZipFileEntry
        }
        internal ZipStorer.ZipFileEntry zfe; // This is the ZipFileEntry where the stream is stored

        #endregion Fields

        #region Constructors

        // This constructor is called when creating the stream from the source template
        public gStream(OoXml doc, ZipStorer zip, ZipStorer.ZipFileEntry z)
        {
            Document = doc;                                                                                                     // Save a reference to the document
            zfe = z;                                                                                                            // Store the ZipFileEntry
        }
Beispiel #16
0
        private void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            UpdateControlState(() =>
            {
                DownloadVersionText.Text = $"正在安装{_currentInstallVersionName}版本的更新包";
            });
            string fileName;
            string contentDisposition = _webClient.ResponseHeaders["Content-Disposition"] ?? string.Empty;

            if (string.IsNullOrEmpty(contentDisposition))
            {
                fileName = Path.GetFileName(_webClient.ResponseUri.LocalPath);
            }
            else
            {
                fileName = _tryToFindFileName(contentDisposition, "filename=");
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = _tryToFindFileName(contentDisposition, "filename*=UTF-8''");
                }
            }
            var tempPath = Path.Combine(Path.GetTempPath(), fileName);

            try
            {
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
                File.Move(_tempFile, tempPath);
            }
            catch (Exception ex)
            {
                UpdateControlState(() =>
                {
                    DownloadVersionText.Text = $"安装{_currentInstallVersionName}版本的更新包失败," + ex.Message;
                });
                _webClient = null;
                return;
            }
            var path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

            ZipStorer zip = ZipStorer.Open(tempPath, FileAccess.Read);

            List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

            for (var index = 0; index < dir.Count; index++)
            {
                ZipStorer.ZipFileEntry entry = dir[index];
                zip.ExtractFile(entry, Path.Combine(path, entry.FilenameInZip));
                int progress = (index + 1) * 100 / dir.Count;;
                UpdateControlState(() =>
                {
                    DownloadProgressBar.Value = progress;
                });
                UpdateControlState(() =>
                {
                    DownloadProgressText.Text = progress + "%";
                });
            }
            zip.Close();

            UpdateControlState(() =>
            {
                DownloadVersionText.Text = $"版本{_currentInstallVersionName}安装成功";
            });
            UpdateControlState(() =>
            {
                DownloadProgressText.Text = string.Empty;
            });
            UpdateControlState(() =>
            {
                CurrentVersion.Content = _currentInstallVersionName;
            });
        }