C#比较两文件内容是否完全一样

                                                                                     C#比较两文件内容是否完全一样

个人归纳出比较两个文件内容是否完全一样的方法,详情如下:

一.逐一比较字节数

private bool CompareFile(string firstFile, string secondFile)
{
     if (!File.Exists(firstFile) || !File.Exists(secondFile)) {
         return false;
     }
     if (firstFile == secondFile) {
         return true;
     }
     int firstFileByte = 0;
     int secondFileByte = 0;
     FileStream secondFileStream = new FileStream(secondFile, FileMode.Open);
     FileStream firstFileStream = new FileStream(firstFile, FileMode.Open);
     if (firstFileStream.Length != secondFileStream.Length) {
         firstFileStream.Close();
         secondFileStream.Close();
         return false;
     }
     do
     {
         firstFileByte = firstFileStream.ReadByte();
         secondFileByte = secondFileStream.ReadByte();
     } while ((firstFileByte == secondFileByte) && (firstFileByte != -1)) ;
     firstFileStream.Close();
     secondFileStream.Close();
     return (firstFileByte == secondFileByte);
}

二.逐行比较内容

private bool CompareFileEx(string firstFile, string secondFile)
{
    if (!File.Exists(firstFile) || !File.Exists(secondFile)) {
        return false;
    }
    if (firstFile == secondFile) {
        return true;
    }
    string firstFileLine = string.Empty;
    string secondFileLine = string.Empty;
    StreamReader secondFileStream = new StreamReader(secondFile, Encoding.Default);
    StreamReader firstFileStream = new StreamReader(firstFile, Encoding.Default);
    do
    {
        firstFileLine = firstFileStream.ReadLine();
        secondFileLine = secondFileStream.ReadLine();
    } while ((firstFileLine == secondFileLine) && (firstFileLine != null));
    firstFileStream.Close();
    secondFileStream.Close();
    return (firstFileLine == secondFileLine);
}

三.比较哈希码

private bool CompareFileExEx(string firstFile, string secondFile)
{
    if (!File.Exists(firstFile) || !File.Exists(secondFile)) {
        return false;
    }
    if (firstFile == secondFile) {
        return true;
    }
    using (HashAlgorithm hash = HashAlgorithm.Create())
    {
        using (FileStream firstStream = new FileStream(firstFile, FileMode.Open), 
              secondStream = new FileStream(secondFile, FileMode.Open))
        {
            byte[] firstHashByte = hash.ComputeHash(firstStream);
            byte[] secondHashByte = hash.ComputeHash(secondStream);
            string firstString = BitConverter.ToString(firstHashByte); 
            string secondString = BitConverter.ToString(secondHashByte);
            return (firstString == secondString);
        }
    }
}

三种方法各有利弊,可根据具体情况具体分析,欢迎大家提出建议。

发布了18 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/csdn_zhangchunfeng/article/details/81093196