星期三, 1月 25, 2006

[.Net]CheckSum

CheckSum 是一個很簡單的檢查方法,把內容拆解成一堆 byte (或word,dword), 如果把這些 bytes 相加起來得到的值一致,表示內容"應該"是沒問題.

using System;
using System.IO;
using System.Collections;


public class CheckSum
{
    private long sum=0;
    
    public CheckSum()
    {

    }

    public void Add( int i )
    {
        sum += i;
    }
    
    public void Add( byte b )
    {
        sum += b;
    }
    
    public long GetCheckSum()
    {
        return sum;
    }
}


public class MyClass
{
    public static void Main()
    {
        string filename;
        FileStream fs=null;
        CheckSum sum = new CheckSum();
        
        //Open the stream and read it back.
        Console.Write( "Please input filename:" );
        filename = Console.ReadLine();
        Console.WriteLine( "Trying to read {0}", filename );
        
        if( File.Exists( filename ) )
            Console.WriteLine( "{0} is existed.", filename );

        try
        {
            fs = File.Open( filename, FileMode.Open, FileAccess.Read );
            
            if( fs.CanRead )
            {
                int value=0;
                
                while( (value = fs.ReadByte()) >= 0)
                {
                    sum.Add( value );
                }
                

                Console.WriteLine( "Checksum = {0,8:x}", sum.GetCheckSum() );
            }
            else
                Console.WriteLine( "Cannot be read" );
        }
        catch( Exception ex )
        {
            Console.WriteLine( ex.Message );
        }
        finally
        {
            fs.Close();

        }
        

        RL();
    }
    
    #region Helper methods
    private static void RL()
    {
        Console.ReadLine();    
    }
    #endregion
}

沒有留言: