Compare binary files in C#

后端 未结 6 2087
渐次进展
渐次进展 2020-12-07 18:09

I want to compare two binary files. One of them is already stored on the server with a pre-calculated CRC32 in the database from when I stored it originally.

I know

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 18:30

    This is how I would do it if you didn't want to rely on crc:

        /// 
        /// Binary comparison of two files
        /// 
        /// the file to compare
        /// the other file to compare
        /// a value indicateing weather the file are identical
        public static bool CompareFiles(string fileName1, string fileName2)
        {
            FileInfo info1 = new FileInfo(fileName1);
            FileInfo info2 = new FileInfo(fileName2);
            bool same = info1.Length == info2.Length;
            if (same)
            {
                using (FileStream fs1 = info1.OpenRead())
                using (FileStream fs2 = info2.OpenRead())
                using (BufferedStream bs1 = new BufferedStream(fs1))
                using (BufferedStream bs2 = new BufferedStream(fs2))
                {
                    for (long i = 0; i < info1.Length; i++)
                    {
                        if (bs1.ReadByte() != bs2.ReadByte())
                        {
                            same = false;
                            break;
                        }
                    }
                }
            }
    
            return same;
        }
    

提交回复
热议问题