高手请关注:WinCE6 用C#程序进行2个文件比较,使用Hashcode计算值比较就可能失败,但是用byte比较却通过。请问什么原因?
先生成一个由ramdom的数据产生的大约3M的文件。
然后复制这个文件。
然后进行这2个文件的对比。
我的问题是,如果用Hashcode比较,在某些时候可以通过,比如生成和复制文件到CE的temp文件夹下。但是有些时候不成功,比如生成和复制文件到SD卡中。
大致的代码思路如下:
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}
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); } }