首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 實作檔案分割與合併工具:FileStream、BinaryReader、BinaryWriter 完整教學

     編輯:關於C#

應用場景

大型檔案(影片、映像檔、備份)超過儲存媒體容量(如 USB、光碟、早期軟碟)時,需分割為多個小檔案分批攜帶,目的端再合併還原。

核心類別 (System.IO)

類別角色
FileStream檔案位元組串流,支援同步/非同步讀寫、定位、鎖定
BinaryReader從串流讀取基本型別 (ReadBytes, ReadInt32, ReadString...)
BinaryWriter向串流寫入基本型別 (Write, WriteBytes...)

本範例採用同步模式,程式碼簡單且不易出錯。

第一部份:檔案分割器

介面元件

  • OpenFileDialog - 選擇大檔案
  • ComboBox - 分割大小 (720K/1440K/2880K...)
  • TextBox - 顯示來源檔案路徑、輸出目錄
  • ProgressBar - 顯示進度
  • Button - 選擇檔案、執行分割

分割器介面

核心分割邏輯


private void btnSplit_Click(object sender, EventArgs e)
{
    int chunkSize = int.Parse(cboSize.Text) * 1024; // KB → Bytes
    string srcFile = txtSource.Text;
    string outDir = txtOutputDir.Text;

    // 清空/建立輸出目錄
    if (Directory.Exists(outDir)) Directory.Delete(outDir, true);
    Directory.CreateDirectory(outDir);

    using (FileStream fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
    using (BinaryReader reader = new BinaryReader(fs))
    {
        long totalChunks = fs.Length / chunkSize;
        if (fs.Length % chunkSize != 0) totalChunks++;

        progressBar1.Maximum = (int)totalChunks;
        progressBar1.Value = 0;

        // 取得副檔名
        string ext = Path.GetExtension(srcFile).TrimStart('.');

        for (int i = 1; i <= totalChunks; i++)
        {
            // 輸出檔名:0001.avi, 0002.avi...
            string outFile = Path.Combine(outDir, $"{i:D4}.{ext}");

            using (FileStream outFs = new FileStream(outFile, FileMode.Create))
            using (BinaryWriter writer = new BinaryWriter(outFs))
            {
                byte[] buffer = reader.ReadBytes(chunkSize);
                writer.Write(buffer);
            }

            progressBar1.Value = i;
        }
    }
    MessageBox.Show("分割完成!");
    progressBar1.Value = 0;
}

第二部份:檔案合併器

介面元件

  • OpenFileDialog - 選擇分割檔案目錄中任一檔案 (以取得目錄)
  • TextBox - 顯示選取檔案、輸入合併後檔名
  • ProgressBar、Button - 同分割器

合併器介面

核心合併邏輯


string sourceDir = ""; // 儲存分割檔目錄

private void btnSelect_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        txtSelected.Text = openFileDialog1.FileName;
        // 取得目錄路徑
        sourceDir = Path.GetDirectoryName(openFileDialog1.FileName);
        btnMerge.Enabled = true;
    }
}

private void btnMerge_Click(object sender, EventArgs e)
{
    string outFile = txtOutput.Text;
    string[] files = Directory.GetFiles(sourceDir);
    Array.Sort(files); // 確保 0001, 0002... 順序

    progressBar1.Maximum = files.Length;
    progressBar1.Value = 0;

    using (FileStream outFs = new FileStream(outFile, FileMode.Create))
    using (BinaryWriter writer = new BinaryWriter(outFs))
    {
        foreach (string file in files)
        {
            using (FileStream inFs = new FileStream(file, FileMode.Open))
            using (BinaryReader reader = new BinaryReader(inFs))
            {
                byte[] buffer = reader.ReadBytes((int)inFs.Length);
                writer.Write(buffer);
            }
            progressBar1.Value++;
        }
    }
    MessageBox.Show("合併完成!");
    progressBar1.Value = 0;
}

關鍵技術細節

  • 檔名排序:合併時必須 Array.Sort 確保分割檔按序寫入,否則檔案損毀。
  • 緩衝區大小:ReadBytes(chunkSize) 一次讀取分割塊大小,記憶體效率佳。
  • using 區塊:確保串流正確關閉釋放檔案鎖定,即使發生例外。
  • 副檔名保留:分割檔保留原始副檔名,方便識別與關聯。

執行畫面

分割執行中

合併執行中

總結

掌握 FileStream、BinaryReader、BinaryWriter 三大核心類別,即可輕鬆實作檔案分割合併、備份還原、格式轉換等二進位檔案處理任務。同步模式適合教學與中小型檔案;大檔案高效能場景可改用非同步 BeginRead/EndRead、MemoryMappedFile 或 FileStream.CopyToAsync。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved