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

C# 檔案分割合併工具(七):合併程式完整實作與專案總結

     編輯:關於C語言

合併程式核心程式碼

命名空間引入

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Text;
using System.Data.OleDb;

全域變數

public string sDirectoryName = "";  // 合併檔案所在目錄

選擇檔案按鈕 - 取得目錄

private void button2_Click(object sender, EventArgs e)
{
    openFileDialog1.Title = "請選擇要合併的第一個檔案";
    if (openFileDialog1.ShowDialog() == DialogResult.OK 
        && openFileDialog1.FileName != "")
    {
        textBox1.Text = openFileDialog1.FileName;
    }
    
    // 解析目錄路徑
    string[] path = openFileDialog1.FileName.Split('\\');
    string dir = "";
    for (int i = 0; i < path.Length - 1; i++)
        dir += path[i] + "\\";
    
    button1.Enabled = true;
    sDirectoryName = dir;
}

執行合併按鈕

private void button1_Click(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles(sDirectoryName);
    int count = files.Length;
    
    progressBar1.Maximum = count;
    
    using (FileStream outFs = new FileStream(textBox2.Text, FileMode.OpenOrCreate))
    using (BinaryWriter writer = new BinaryWriter(outFs))
    {
        for (int i = 0; i < count; i++)
        {
            using (FileStream inFs = new FileStream(files[i], FileMode.Open))
            using (BinaryReader reader = new BinaryReader(inFs))
            {
                writer.Write(reader.ReadBytes((int)inFs.Length));
            }
            progressBar1.Value = i + 1;
        }
    }
    
    MessageBox.Show("成功合併!");
    progressBar1.Value = 0;
}

執行畫面

合併程式執行介面

專案總結

Visual C# 檔案處理能力源自 System.IO 命名空間。分割合併屬較複雜的檔案編程應用,核心僅需三大類:

  • FileStream:檔案位元組串流存取
  • BinaryReader:二進位資料讀取
  • BinaryWriter:二進位資料寫入

掌握這三類即掌握檔案編程精髓。其他類別或用法相似、或結構更簡單。希望本系列助您精通 C# 檔案編程。

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