大檔案傳輸、備份常需分割成小檔案。本文實作純 C# 命令列工具 filesplitcon,支援 分割 (指定份數) 與 合併 (依清單檔),使用 FileStream/StreamReader/StreamWriter 進行高效位元組流處理,編譯後僅 6.5 KB,可部署為系統命令。
using System;
using System.IO;
namespace filesplitcon
{
class Program
{
static void Main(string[] args)
{
if (args.Length < 2) { ShowUsage(); return; }
if (args[0] == "s") // Split
{
string srcFile = args[1];
int parts = int.Parse(args[2]);
using (FileStream fr = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
{
int chunkSize = (int)(fr.Length / parts);
using (StreamWriter list = new StreamWriter(srcFile + ".list", false))
{
for (int i = 1; i <= parts; i++)
{
byte[] buffer = new byte[chunkSize];
int read = fr.Read(buffer, 0, chunkSize);
using (FileStream fw = new FileStream($"{srcFile}.{i}", FileMode.CreateNew, FileAccess.Write))
{
fw.Write(buffer, 0, read);
list.WriteLine($"{srcFile}.{i}");
}
}
// 處理剩餘位元組
if (fr.Position < fr.Length)
{
int remain = (int)(fr.Length - fr.Position);
byte[] buffer = new byte[remain];
fr.Read(buffer, 0, remain);
using (FileStream fw = new FileStream($"{srcFile}.{parts + 1}", FileMode.CreateNew, FileAccess.Write))
{
fw.Write(buffer, 0, remain);
list.WriteLine($"{srcFile}.{parts + 1}");
}
}
list.Flush();
}
}
Console.WriteLine("檔案分割完成");
}
else if (args[0] == "m") // Merge
{
string listFile = args[1] + ".list";
string destFile = args[1];
using (StreamReader list = new StreamReader(listFile))
using (FileStream fw = new FileStream(destFile, FileMode.Append, FileAccess.Write))
{
string partFile;
while ((partFile = list.ReadLine()) != null)
{
using (FileStream fr = new FileStream(partFile, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[fr.Length];
fr.Read(buffer, 0, buffer.Length);
fw.Write(buffer, 0, buffer.Length);
}
}
}
Console.WriteLine("檔案合併完成");
}
else ShowUsage();
}
static void ShowUsage()
{
Console.WriteLine("用法:");
Console.WriteLine(" filesplitcon s <檔案> <份數> - 分割檔案");
Console.WriteLine(" filesplitcon m <合併後檔名> - 合併檔案 (需 .list 清單)");
}
}
}
# 分割 w2ksp3.exe 為 4 份
filesplitcon s w2ksp3.exe 4
# 產生:w2ksp3.exe.1 ~ .4、.list
# 合併 (將 .1~.4 與 .list 放同目錄)
filesplitcon m w2ksp3.exe
# 還原 w2ksp3.exe
| 檔案 | 說明 |
|---|---|
原檔名.1 ~ .N | 分割後的二進位區塊 |
原檔名.list | 文字清單,每行一個分割檔名,合併時依序讀取 |
Read/Write,記憶體佔用固定 (chunkSize),支援超大檔 (GB 級)。C:\Windows 或 PATH 目錄即可全域呼叫。FileOptions.SequentialScan 優化大檔案讀取。不到 100 行代碼實作實用的檔案分割合併工具,展示 FileStream 位元組流操作核心技巧,亦為學習 C# I/O、命令列參數解析、錯誤處理的優秀練習專案。