zoukankan      html  css  js  c++  java
  • C#比较两文件内容是否完全一样

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

    ————————————————

    原文链接:https://blog.csdn.net/csdn_zhangchunfeng/article/details/81093196

    一.逐一比较字节数

    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);
    }
    }
    }
    三种方法各有利弊,可根据具体情况具体分析,欢迎大家提出建议。

  • 相关阅读:
    select选择框去掉默认的下拉箭头
    网站怎么添加ico小图标
    js实现逐字打印效果,文本逐字显示
    jQuery实现消息列表循环垂直向上滚动
    滤镜图片变黑白+图片模糊
    多选下拉框(select 下拉多选)
    JavaScript 数组相关基础方法
    h5+ IOS App中判断本地文件是否存在 plus.io.resolveLocalFileSystemURL()
    h5+ IOS App中取消视频默认全屏播放
    C# 多线程与队列操作小练刀
  • 原文地址:https://www.cnblogs.com/chinayixia/p/12513491.html
Copyright © 2011-2022 走看看