当前位置: 代码迷 >> WinCE >> 高手请关注:WinCE6 用C#程序进行2个文件比较,使用Hashcode计算值比较就可能失败,但是用byte比较却通过。请教什么原因
  详细解决方案

高手请关注:WinCE6 用C#程序进行2个文件比较,使用Hashcode计算值比较就可能失败,但是用byte比较却通过。请教什么原因

热度:10   发布时间:2016-04-28 13:17:27.0
高手请关注:WinCE6 用C#程序进行2个文件比较,使用Hashcode计算值比较就可能失败,但是用byte比较却通过。请问什么原因?
先生成一个由ramdom的数据产生的大约3M的文件。
然后复制这个文件。
然后进行这2个文件的对比。

我的问题是,如果用Hashcode比较,在某些时候可以通过,比如生成和复制文件到CE的temp文件夹下。但是有些时候不成功,比如生成和复制文件到SD卡中。
大致的代码思路如下:

C# code
bytes = new byte[1];rand.NextBytes(bytes);newFile.Append(bytes[0], 2000000 + rand.Next(1000000, 2000000));//ComputeHash from firstFile and get a byte[].//System.Security.Cryptography.HashAlgorithmFileStream fs1 = File.Open(firstFile);String hash1 = String.Empty;foreach (byte b in HashAlgorithm.ComputeHash(fs1)) hash1 += b.ToString("x2").ToLower();//copy from firstFile to secondFilefInfo.CopyTo(secondFile, true);//ComputeHash from secondFile and get a byte[].FileStream fs2 = File.Open(secondFile);String hash = String.Empty;foreach (byte b in HashAlgorithm.ComputeHash(fs2)) hash2 += b.ToString("x2").ToLower();//compare two hashif (!hash2.Equals(hash1)){     //fail}


可是另外写了一段代码,只是用简单的byte来一个一个比较。不论在哪个盘上,都是通过的。
C# code
        private bool FileCompare(string file1Path, string file2Path)         {             //if two file are point to one file. it is same            if(file1Path == file2Path)             {                 return true;            }                         int file1byte = 0;             int file2byte = 0;                          using(FileStream fs1 = new FileStream(file1Path, FileMode.Open),                              fs2 = new FileStream(file2Path, FileMode.Open))             {                 if(fs1.Length != fs2.Length)                 {                     fs1.Close();                     fs2.Close();                     return false;                 }                do                {                    //read each byte from each file                    file1byte = fs1.ReadByte();                    file2byte = fs2.ReadByte();                }                while ((file1byte == file2byte) && (file1byte != -1));                                fs1.Close();                fs2.Close();                                return ((file1byte - file2byte) == 0);             }        } 


是什么导致hashcode的比较会失败?
另外,奇怪的是相同的代码在Windows Mobile6 或者是WinCE5 却不会出现问题。两个方式进行比较都是通过的。

------解决方案--------------------
你先把hash1和hash2输出出来看下哪里不一样
------解决方案--------------------


String hash = String.Empty;
foreach (byte b in HashAlgorithm.ComputeHash(fs2)) hash2 += b.ToString("x2").ToLower();

你这里上面申明的是hash不是hash2,你的hash2在哪里?全局的?那执行的时候就没有 = String.Empty;的初始化了
------解决方案--------------------
字节比较是对的,只能说明是程序的问题
------解决方案--------------------
BYTE 是正确的
------解决方案--------------------
Binary比较即可
  相关解决方案