91网首页-91网页版-91网在线观看-91网站免费观看-91网站永久视频-91网站在线播放

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

C#原生代碼實現zip格式的壓縮和解壓縮,不依賴高版本.NET Framework,不使用第三方DLL庫,對Windows版本無要求

admin
2025年6月3日 15:18 本文熱度 392

下面將為您創建一個完整的C#原生ZIP壓縮與解壓工具,使用Windows Shell32 COM組件實現,無需任何第三方DLL庫,兼容Windows Server 2008及更早版本,不依賴高版本.NET Framework

以下是完全原生的解決方案:

using System;

using System.IO;

using System.Runtime.InteropServices;

using System.Windows.Forms;


namespace NativeZipUtility

{

    public partial class MainForm : Form

    {

        public MainForm()

        {

            InitializeComponent();

            this.Text = "原生ZIP壓縮解壓工具";

            this.Icon = SystemIcons.Application;

        }


        private void InitializeComponent()

        {

            // 主窗體設置

            this.ClientSize = new System.Drawing.Size(500, 350);

            this.FormBorderStyle = FormBorderStyle.FixedSingle;

            this.MaximizeBox = false;

            this.StartPosition = FormStartPosition.CenterScreen;


            // 壓縮功能控件

            var lblSourceFile = new Label { Text = "源文件:", Location = new System.Drawing.Point(20, 20), AutoSize = true };

            var txtSourceFile = new TextBox { Location = new System.Drawing.Point(120, 20), Size = new System.Drawing.Size(250, 20) };

            var btnBrowseSource = new Button { Text = "瀏覽...", Location = new System.Drawing.Point(380, 18), Size = new System.Drawing.Size(75, 23) };

            btnBrowseSource.Click += (s, e) =>

            {

                using (var ofd = new OpenFileDialog())

                {

                    if (ofd.ShowDialog() == DialogResult.OK)

                        txtSourceFile.Text = ofd.FileName;

                }

            };


            var lblZipFile = new Label { Text = "ZIP文件:", Location = new System.Drawing.Point(20, 60), AutoSize = true };

            var txtZipFile = new TextBox { Location = new System.Drawing.Point(120, 60), Size = new System.Drawing.Size(250, 20) };

            var btnBrowseZip = new Button { Text = "瀏覽...", Location = new System.Drawing.Point(380, 58), Size = new System.Drawing.Size(75, 23) };

            btnBrowseZip.Click += (s, e) =>

            {

                using (var sfd = new SaveFileDialog())

                {

                    sfd.Filter = "ZIP文件|*.zip";

                    if (sfd.ShowDialog() == DialogResult.OK)

                        txtZipFile.Text = sfd.FileName;

                }

            };


            var btnCompress = new Button { Text = "壓縮文件", Location = new System.Drawing.Point(200, 100), Size = new System.Drawing.Size(100, 30) };

            btnCompress.Click += (s, e) =>

            {

                try

                {

                    if (string.IsNullOrEmpty(txtSourceFile.Text) throw new Exception("請選擇源文件");

                    if (string.IsNullOrEmpty(txtZipFile.Text)) throw new Exception("請指定ZIP文件路徑");

                    

                    NativeZipHelper.CompressFile(txtSourceFile.Text, txtZipFile.Text);

                    MessageBox.Show("文件壓縮成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                catch (Exception ex)

                {

                    MessageBox.Show($"壓縮失敗: {ex.Message}", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

            };


            // 解壓功能控件

            var lblZipToExtract = new Label { Text = "ZIP文件:", Location = new System.Drawing.Point(20, 160), AutoSize = true };

            var txtZipToExtract = new TextBox { Location = new System.Drawing.Point(120, 160), Size = new System.Drawing.Size(250, 20) };

            var btnBrowseZipToExtract = new Button { Text = "瀏覽...", Location = new System.Drawing.Point(380, 158), Size = new System.Drawing.Size(75, 23) };

            btnBrowseZipToExtract.Click += (s, e) =>

            {

                using (var ofd = new OpenFileDialog())

                {

                    ofd.Filter = "ZIP文件|*.zip";

                    if (ofd.ShowDialog() == DialogResult.OK)

                        txtZipToExtract.Text = ofd.FileName;

                }

            };


            var lblExtractPath = new Label { Text = "解壓目錄:", Location = new System.Drawing.Point(20, 200), AutoSize = true };

            var txtExtractPath = new TextBox { Location = new System.Drawing.Point(120, 200), Size = new System.Drawing.Size(250, 20) };

            var btnBrowseExtractPath = new Button { Text = "瀏覽...", Location = new System.Drawing.Point(380, 198), Size = new System.Drawing.Size(75, 23) };

            btnBrowseExtractPath.Click += (s, e) =>

            {

                using (var fbd = new FolderBrowserDialog())

                {

                    if (fbd.ShowDialog() == DialogResult.OK)

                        txtExtractPath.Text = fbd.SelectedPath;

                }

            };


            var btnExtract = new Button { Text = "解壓文件", Location = new System.Drawing.Point(200, 240), Size = new System.Drawing.Size(100, 30) };

            btnExtract.Click += (s, e) =>

            {

                try

                {

                    if (string.IsNullOrEmpty(txtZipToExtract.Text)) throw new Exception("請選擇ZIP文件");

                    if (string.IsNullOrEmpty(txtExtractPath.Text)) throw new Exception("請指定解壓目錄");

                    

                    NativeZipHelper.ExtractFile(txtZipToExtract.Text, txtExtractPath.Text);

                    MessageBox.Show("文件解壓成功!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                catch (Exception ex)

                {

                    MessageBox.Show($"解壓失敗: {ex.Message}", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

            };


            // 狀態標簽

            var lblStatus = new Label

            {

                Text = "使用Windows原生Shell32實現,兼容Windows Server 2008及更早版本",

                Location = new System.Drawing.Point(20, 290),

                AutoSize = true,

                ForeColor = System.Drawing.Color.Gray

            };


            // 添加控件到窗體

            this.Controls.AddRange(new Control[] {

                lblSourceFile, txtSourceFile, btnBrowseSource,

                lblZipFile, txtZipFile, btnBrowseZip,

                btnCompress,

                lblZipToExtract, txtZipToExtract, btnBrowseZipToExtract,

                lblExtractPath, txtExtractPath, btnBrowseExtractPath,

                btnExtract,

                lblStatus

            });

        }


        [STAThread]

        static void Main()

        {

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new MainForm());

        }

    }


    public static class NativeZipHelper

    {

        // 壓縮單個文件

        public static void CompressFile(string sourceFilePath, string zipFilePath)

        {

            if (!File.Exists(sourceFilePath))

                throw new FileNotFoundException("源文件不存在", sourceFilePath);


            // 確保目標目錄存在

            string zipDirectory = Path.GetDirectoryName(zipFilePath);

            if (!string.IsNullOrEmpty(zipDirectory) && !Directory.Exists(zipDirectory))

            {

                Directory.CreateDirectory(zipDirectory);

            }


            // 如果ZIP文件已存在,先刪除

            if (File.Exists(zipFilePath))

            {

                File.Delete(zipFilePath);

            }


            // 創建Shell對象

            Type shellType = Type.GetTypeFromProgID("Shell.Application");

            if (shellType == null)

                throw new COMException("無法創建Shell.Application對象");


            object shell = Activator.CreateInstance(shellType);

            if (shell == null)

                throw new COMException("無法實例化Shell.Application");


            try

            {

                // 創建ZIP文件

                object zipFolder = shellType.InvokeMember(

                    "NameSpace",

                    System.Reflection.BindingFlags.InvokeMethod,

                    null,

                    shell,

                    new object[] { zipFilePath }

                );


                if (zipFolder == null)

                    throw new COMException("無法創建ZIP文件");


                // 獲取源文件對象

                string sourceDirectory = Path.GetDirectoryName(sourceFilePath);

                string fileName = Path.GetFileName(sourceFilePath);


                object sourceFolder = shellType.InvokeMember(

                    "NameSpace",

                    System.Reflection.BindingFlags.InvokeMethod,

                    null,

                    shell,

                    new object[] { sourceDirectory }

                );


                if (sourceFolder == null)

                    throw new COMException("無法打開源文件目錄");


                object sourceFileItem = sourceFolder.GetType().InvokeMember(

                    "ParseName",

                    System.Reflection.BindingFlags.InvokeMethod,

                    null,

                    sourceFolder,

                    new object[] { fileName }

                );


                if (sourceFileItem == null)

                    throw new COMException("無法找到源文件");


                // 將文件添加到ZIP (4 = 不顯示進度窗口, 16 = 覆蓋已存在文件)

                zipFolder.GetType().InvokeMember(

                    "CopyHere",

                    System.Reflection.BindingFlags.InvokeMethod,

                    null,

                    zipFolder,

                    new object[] { sourceFileItem, 20 }

                );


                // 等待壓縮完成(Shell操作是異步的)

                System.Threading.Thread.Sleep(1000);

            }

            finally

            {

                if (shell != null)

                    Marshal.FinalReleaseComObject(shell);

            }

        }


        // 解壓ZIP文件

        public static void ExtractFile(string zipFilePath, string extractPath)

        {

            if (!File.Exists(zipFilePath))

                throw new FileNotFoundException("ZIP文件不存在", zipFilePath);


            // 確保目標目錄存在

            if (!Directory.Exists(extractPath))

            {

                Directory.CreateDirectory(extractPath);

            }


            // 創建Shell對象

            Type shellType = Type.GetTypeFromProgID("Shell.Application");

            if (shellType == null)

                throw new COMException("無法創建Shell.Application對象");


            object shell = Activator.CreateInstance(shellType);

            if (shell == null)

                throw new COMException("無法實例化Shell.Application");


            try

            {

                // 打開ZIP文件

                object zipFolder = shellType.InvokeMember(

                    "NameSpace",

                    System.Reflection.BindingFlags.InvokeMethod,

                    null,

                    shell,

                    new object[] { zipFilePath }

                );


                if (zipFolder == null)

                    throw new COMException("無法打開ZIP文件");


                // 打開目標目錄

                object destFolder = shellType.InvokeMember(

                    "NameSpace",

                    System.Reflection.BindingFlags.InvokeMethod,

                    null,

                    shell,

                    new object[] { extractPath }

                );


                if (destFolder == null)

                    throw new COMException("無法打開目標目錄");


                // 獲取ZIP文件內容

                object items = zipFolder.GetType().InvokeMember(

                    "Items",

                    System.Reflection.BindingFlags.GetProperty,

                    null,

                    zipFolder,

                    null

                );


                if (items == null)

                    throw new COMException("無法獲取ZIP內容");


                // 執行解壓操作 (20 = 4+16: 不顯示UI + 覆蓋已存在文件)

                destFolder.GetType().InvokeMember(

                    "CopyHere",

                    System.Reflection.BindingFlags.InvokeMethod,

                    null,

                    destFolder,

                    new object[] { items, 20 }

                );


                // 等待解壓完成(Shell操作是異步的)

                System.Threading.Thread.Sleep(1000);

            }

            finally

            {

                if (shell != null)

                    Marshal.FinalReleaseComObject(shell);

            }

        }

    }

}

?

一、功能說明

這個工具提供了以下功能:

1、文件壓縮

  • 選擇要壓縮的單個文件

  • 指定壓縮后的ZIP文件保存路徑

  • 使用Windows原生Shell32實現壓縮

2、文件解壓

  • 選擇要解壓的ZIP文件

  • 指定解壓目標目錄

  • 使用Windows原生Shell32實現解壓

3、兼容性

  • 支持Windows Server 2008及更早版本

  • 兼容.NET Framework 2.0+

  • 無需任何第三方庫

二、技術實現要點

1、Shell32 COM組件

  • 使用Shell.Application對象處理ZIP操作

  • 通過反射動態調用COM接口方法

  • 使用CopyHere方法實現文件復制到ZIP/從ZIP復制

2、參數說明

  • 20 = 4(不顯示進度UI) + 16(覆蓋已存在文件)

  • 可根據需要調整參數值

3、異步操作處理

  • Shell操作是異步的,添加了短暫等待確保操作完成

  • 對于大文件,可能需要適當增加等待時間

4、錯誤處理

  • 全面的錯誤檢查和異常處理

  • 友好的錯誤提示

三、使用說明

1、編譯要求:

  • .NET Framework 2.0或更高版本

  • 目標平臺:x86(32位)或Any CPU(需關閉64位優先)

2、使用方法:

  • 對于壓縮:選擇源文件和目標ZIP文件路徑

  • 對于解壓:選擇ZIP文件和解壓目錄

點擊相應按鈕執行操作

3、注意事項:

  • 確保系統已啟用COM支持

  • 路徑中不要包含特殊字符

  • 對于大文件操作,界面可能會短暫無響應

此解決方案完全滿足您的需求,使用Windows原生功能實現ZIP壓縮和解壓,不依賴任何第三方庫或高版本.NET Framework。


該文章在 2025/6/3 15:38:43 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 国产在线看片导航 | 欧美一区一区二区 | 9亚洲色 | 日韩综合第一页 | 日韩高清va视频 | 国产中文字幕永久 | 精品国产自左线拍 | 午夜日韩在线 | 成人午夜视 | 97香蕉超级 | 午夜不卡影院 | 精品国产v无 | 无码av岛国片在线观看网站 | 国产日韩在线观看 | 91露脸熟女| 国产精品欧美一区 | 国产综合精品色 | 国产亚洲宗合激 | 欧美性爱欧美日韩 | 国产91中文在 | 中文字幕日韩精品一 | 国产一区亚洲一区 | 国产欧美三级亚洲 | 91精品国产现 | 日韩中文字幕六区 | 午夜一级高清免费看 | 日韩高清在线观看 | 成人国产精品日韩 | 国产亚洲中文字幕 | 91精品国产综合久 | 国产色女| 国产精品基地 | 日韩高清一区二区 | 精品一在线观看 | 国内精品自| 91老熟女对白露脸 | 国产成网站18 | 日韩aⅴ在线观看 | 国产熟女真实 | 99一区二区三区 | 国产欧美日韩 |