compare

Hi

how can i compare two text files

i mean the text in these files




Answer this question

compare

  • Reyad

    You can also creating hash values and compare, like the way SourceSafe default to.
    Check out GetHashFromFile method in MSDN (http://msdn2.microsoft.com/en-us/library/dchdsb9x.aspx).

    Hope it helps,
    Thi

  • skipsizemore

    Indeed, very helpfull Truong Hong Thi!

    Here is a little code example:

    using(FileStream file1 = new FileStream("@c:\file1.txt", FileMode.Open, FileAccess.Read ))
    using(FileStream file2 = new FileStream("@c:\file2.txt", FileMode.Open, FileAccess.Read ))
    {
        MD5 md5 = new MD5CryptoServiceProvider();

        byte[] hash1 = md5.ComputeHash( file1 );
        byte[] hash2 = md5.ComputeHash( file2 );

        if( !hash1.Length.Equals( hash2.Length ))
        {
            return false;
        }

        for( int i = 0; i < hash1.Length; i++ )
        {
            if( !hash1[ i ].Equals( hash2[ i ] ))
            {
                return false;
            }
        }

        return true;
    }

     



  • Saul775

    thanks my frind

    but i need to compare two big text files can you help me



  • 12345x123456

    Then here is a little optimalization, but if this is still to slow you need to do it with a block-reader:


    using(StreamReader readerFile1 = new StreamReader(@"c:\file1.txt"))
    using(StreamReader readerFile2 = new StreamReader(@"c:\file2.txt"))
    {
    // Determ of the stream support seeking.
    if( readerFile1.BaseStream.CanSeek && readerFile2.BaseStream.CanSeek )
    {
    if( readerFile1.BaseStream.Length != readerFile2.BaseStream.Length )
    {
    return false;
    }
    }

    string line1 = null;
    string line2 = null;

    while( (line1 = readerFile1.ReadLine() ) != null )
    {
    line2 = readerFile2.ReadLine();

    if( line2 == null )
    {
    return false;
    }
    else
    {
    if( !line1.Equals( line2 ) )
    {
    return false;
    }
    }
    }

    line2 = readerFile2.ReadLine();

    if( line2 == null )
    {
    return true;
    }
    else
    {
    return false;
    }
    }




  • vinod singh

    Thanks all

    You were very helpfull



  • Paul.2010

    For small files you can do this:


    using(StreamReader readerFile1 = new StreamReader(@"c:\file1.txt"))
    using(StreamReader readerFile2 = new StreamReader(@"c:\file2.txt"))
    {
    string file1Content = readerFile1.ReadToEnd();
    string file2Content = readerFile2.ReadToEnd();

    if( file1Content.Equals( file2Content ) )
    {
    // The files are equal.
    }
    }




  • compare