Saturday 3 January 2015

How to check two files are equal or not in asp.net using c#.

compare two file in asp.net


Description:-

In this example we explain that how to compare two file in asp.net or how to check two files content are same or duplicate in asp.net.

Generally file duplication can create problem when we work with lots of  file in our application and most of the aapllication only check file names and creation date or modification date. But in this example we also check the content of two files are equal or duplicate.

Here we compare two file by byte to byte comparision of this two file. Two compare content of the two file in 
asp.net we used one algorithm and it is known as the Hash Algorithm. This algoriyhm is provided my .Net inbuilt and is aim is to compare two file by byte to byte and return result true or false.


Sorting Row data in gridview Gridview Sorting 

How to handle Concurrency in Linq to Sql Concurrency Example 


code.aspx:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="progrebar.aspx.cs" Inherits="progrebar" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Compare two text</title> files in asp.net
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            <label id="lblmsg" runat="server"></label>
        </div>
    </form>
</body>
</html>

code.aspx.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Security.Cryptography;



public partial class progrebar : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {

        string file1 = "D:\\documents\\TextFile1.txt";
        string file2 = "D:\\document\\TextFile2.txt";

        if (File.Exists(file1) && File.Exists(file2))
        {

            HashAlgorithm hashAlgo = HashAlgorithm.Create();

            FileStream stream1 = new FileStream(file1, FileMode.Open);
            FileStream stream2 = new FileStream(file2, FileMode.Open);

            byte[] hash1;
            byte[] hash2;

            hash1 = hashAlgo.ComputeHash(stream1);
            hash2 = hashAlgo.ComputeHash(stream2);

            stream1.Close();
            stream2.Close();

            if (Convert.ToBase64String(hash1) == Convert.ToBase64String(hash2))
            {
                lblmsg.InnerText = "Files are equal";
            }
            else
            {
                lblmsg.InnerText = "Files are not equal";
            }
        }
        else
        {
            lblmsg.InnerText = "One of the file doesn’t exists";
        }

    }
}




0 comments:

Post a Comment