C#で大容量ファイルを分割する方法のサムネイル

📂【C#】大容量ファイルを指定サイズ以下に分割する方法|.NET8対応コード付き

2025年7月17日

✅ はじめに

大容量のファイル(例:2GBや25GBなど)をアップロードやバックアップのために小さなサイズに分割したいケースは多いです。特に「99MB以下」に収めたいというニーズは、クラウド制限やメール添付サイズ制限の影響からも頻繁に見られます。

本記事では、C#(.NET 8)を使って任意のサイズ(今回は99MB)でファイルを安全かつ効率的に分割する方法を、実用的なコード例付きで解説します。

🔍 なぜ99MBなのか?分割サイズの意味

たとえば、2102127857バイトというファイルサイズは、次のように換算されます:

単位計算式結果
GB(10進)2102127857 ÷ 1,000,000,0002.10 GB
GiB(2進)2102127857 ÷ 1,073,741,8241.96 GiB

クラウドや外部ストレージサービスでは、「100MB未満に収める」ことで制限を回避できることがあるため、99MBという制限で分割するのは非常に実用的です。

🛠️ 使用する技術

💡 C#で大容量ファイルを99MB以下に分割するコード


using System;
using System.IO;
using System.Threading.Tasks;

class FileSplitter
{
    static async Task Main()
    {
        string inputFilePath = "largefile.dat";              // 分割したいファイル
        string outputDirectory = "output_parts";             // 出力先フォルダ
        Directory.CreateDirectory(outputDirectory);

        const long maxPartSize = 99L * 1024 * 1024;           // 99MB(= 103,809,024バイト)
        const int bufferSize = 1 * 1024 * 1024;               // 1MBバッファ
        byte[] buffer = new byte[bufferSize];

        using FileStream input = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read);

        int partNumber = 1;
        while (input.Position < input.Length)
        {
            string partFilePath = Path.Combine(outputDirectory, $"part{partNumber:D4}.dat");
            using FileStream output = new FileStream(partFilePath, FileMode.Create, FileAccess.Write);

            long bytesWritten = 0;
            while (bytesWritten < maxPartSize && input.Position < input.Length)
            {
                int bytesToRead = (int)Math.Min(bufferSize, maxPartSize - bytesWritten);
                int read = await input.ReadAsync(buffer.AsMemory(0, bytesToRead));
                if (read == 0) break;

                await output.WriteAsync(buffer.AsMemory(0, read));
                bytesWritten += read;
            }

            Console.WriteLine($"書き出し完了:{partFilePath}({bytesWritten:N0} バイト)");
            partNumber++;
        }

        Console.WriteLine("✅ 全ファイルの分割が完了しました。");
    }
}
      

📁 出力結果例(2GBのファイルを分割)


output_parts/
├── part0001.dat  約99MB
├── part0002.dat  約99MB
├── ...
├── part0021.dat  約66MB(最後)
      

✅ この分割方法のメリット

🧩 応用:ファイルの結合も可能

この方法で分割されたファイルは、後から以下のように結合することも可能です:


using (var output = File.Create("merged.dat"))
{
    for (int i = 1; i <= partNumber; i++)
    {
        string partFile = $"output_parts/part{i:D4}.dat";
        using var input = File.OpenRead(partFile);
        await input.CopyToAsync(output);
    }
}
      

WinUI 3 / XAML の Grid.Width 設定方法

WinUI 3でMenuFlyoutをShowAtで表示する方法【コード付き解説】

MenuFlyoutWinUI 3 で便利なポップアップメニュー

WinUI 3の開発で混乱しがちな「空白のウィンドウ」と「空白のページ」の違い

PowerShellでMSIXアプリ(Storeアプリ)を起動する方法|AppUserModelIdとURIスキーム活用術

Microsoft Storeアプリ更新時のロールアウト設定まとめ

PowerShellでtail -f!WindowsでUTF-8対応のリアルタイムログ監視を実現する方法

Microsoft純正の新しいコンソールエディタ「edit」が復活!| edit.exe インストール方法

Microsoft Authenticatorのオートフィル機能が2025年7月に終了

RuntimeBroker.exeとMsEdgeWebView2.exeとは?Windows 11のプロセスについて

PowerShellでGrapheme Clusterについて処理を考える

業務用ノートパソコンのストレージは暗号化されている?BitLockerの確認と対策方法

【Windows】Volta コマンドライン インストール | Node.jsをバージョン管理する方法

【C# .NET 8 対応】List<string> を重複なしでマージする方法|

【C#】大容量ファイルを指定サイズ以下に分割する方法|.NET8対応コード付き

【C# .NET 8】ファイルから重複行を削除する2つの方法|Distinct vs HashSet

【C#】.emlファイルの本文を読みやすく抽出する方法

WinUI 3 ComboBoxの自作クラスバインドと選択イベント検出方法

switch文でオブジェクトの型を判別する方法

【WPF】Task.Run中にUIを更新する方法

System.Text.Json 9.0.0.0 で FileNotFoundException

C#で改行・カンマ入りのCSVを正しく読み込む方法【.NET8対応】

C#/.NET 8でDateTimeを日本時間でISO 8601形式に変換する方法

【Anker Soundcore Liberty 4】イヤーピース紛失!代替品はAmazonで購入

和暦設定でも安心!C#でISO 8601やカスタム日時文字列を確実にDateTimeに変換