mikan's technical note

仕事&趣味で実験した小技の備忘録です(Linux,windows,DOS等)

MENU

【C#】改行コードCRLF(0x0d0a)形式ファイルを、改行コードLF(0x0a)形式ファイルに変換

//
// 【改行コード CRLF(0x0d0a) -> LF(0x0a)】※Windows7で動作確認済
// (c) 2017 mikan
// ※使用にあたっては利用者の自己責任でお願いします。
//
using System;
using System.IO;

namespace CRLFtoLF
{
    class Program
    {
        static void Main(string[] args)
        {
            string str;

            // ※既存ファイルへの上書きチェック等は別途行ってください
            if (args.Length != 2) {
                Console.WriteLine("パラメータエラー");
                return;
            }

            // 入力ファイルを全て読み込み(byte型)
            FileStream fs1 = new FileStream(args[0], FileMode.Open);
            byte[] data = new byte[fs1.Length];
            fs1.Read(data, 0, data.Length);
            fs1.Close();

            // 出力ファイルオープン(バイナリ形式)
            FileStream fs2 = new FileStream(args[1], FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs2);

            // 1byteずつ書き込み(0x0dを削除)
            for(int i = 0; i < data.Length; i ++) {
                if(data[i] == 0x0d)
                {
                    continue;
                }
                bw.Write(data[i]);
            }

            // 出力ファイルクローズ
            bw.Close();
            fs2.Close();
        }
    }
}