HUSKING - kotteri

技術系Note

【C#】複数のファイルを結合し、一つのファイルにまとめる

複数のファイルを結合して、一つのファイルにまとめてみる
手法は簡単で一つずつファイルを読みだして、結果ファイルに書き出していくだけ


結合するファイル

今回は3つのファイルを結合してみる
※ ファイルのエンコードは"UTF-8(BOM無し)"

  • ファイル1(src1.txt)
┳┻|
┻┳|
┳


  • ファイル2(src2.txt)
┻|_∧
┻┳|ω・)
┳┻|


  • ファイル3(src3.txt)
⊂ノ
┻┳| J


実際のコード

class Program
{
    static void Main(string[] args)
    {
        // EXEパスを取得
        var exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

        // 結合する2つのファイルパス(適当にリストで保持)
        // ファイルはEXEファイルと同じフォルダにあるものとする 
        var srcFilesPath = new List<string>
        {
            System.IO.Path.Combine(System.IO.Path.GetDirectoryName(exePath), "src1.txt"),
            System.IO.Path.Combine(System.IO.Path.GetDirectoryName(exePath), "src2.txt"),
            System.IO.Path.Combine(System.IO.Path.GetDirectoryName(exePath), "src3.txt")
        };

        // 結果ファイルパス
        var dstFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(exePath), "dst.txt");

        // 結合処理
        using (var wfs = new System.IO.FileStream(dstFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write))
        {
            // 結合するファイルを順に読んで、結果ファイルに書き込む
            var rbuf = new byte[1024 * 1024];
            foreach (var srcFilePath in srcFilesPath)
            {
                using (var rfs = new System.IO.FileStream(srcFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    var readByte = 0;
                    var leftByte = rfs.Length;
                 
                    while (leftByte > 0)
                    {
                        // 指定のサイズずつファイルの読み込む
                        readByte = rfs.Read(rbuf, 0, (int)Math.Min(rbuf.Length, leftByte));

                        // 読み込んだ内容を結果ファイルに書き込む
                        wfs.Write(rbuf, 0, readByte);

                        // 残りの読み込みバイト数を更新
                        leftByte -= readByte;
                    }
                }
            }
        }



        Console.ReadKey();
    }
}


結果ファイル(dst.txt)の中身

┳┻|
┻┳|
┳┻|_∧
┻┳|ω・)
┳┻|⊂ノ
┻┳| J