2つのファイルを比較する

2つのファイルをバイナリで比較する関数の例です。
FileStreamを利用するので
using System.IO;
を忘れずに追加してください。

FileCompare関数は一致か否かをboolで返します。
引数は比較したいファイル1とファイル2のファイル名です。
絶対パス付きが望ましいです。

        private bool FileCompare(string file1, string file2)
        {
            if (file1 == file2)
                return true;

            FileStream fs1 = new FileStream(file1, FileMode.Open);
            FileStream fs2 = new FileStream(file2, FileMode.Open);
            int byte1;
            int byte2;
            bool ret = false;

            try
            {
                if (fs1.Length == fs2.Length)
                {
                    do
                    {
                        byte1 = fs1.ReadByte();
                        byte2 = fs2.ReadByte();
                    }
                    while ((byte1 == byte2) && (byte1 != -1));

                    if (byte1 == byte2)
                        ret = true;
                }
            }
            catch
            {
            }
            finally
            {
                fs1.Close();
                fs2.Close();
            }

            return ret;
        }

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)