header
CodePanic! > C#.NET Tips > 今ここ

■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;
        }





Copyright © 2008.07 - shougo suzaki