初学者

导航

如何判断2个文件是否相同(学了就是我的)(C#)

 

  本程序主要靠FileStream到ReadByte函数实现

 ReadByte 是文件流动一个实例函数,会从数据流中读取一个字节,并将读取位置前移一个字节(为什么要说前移,我也搞不清楚,应该跟FileStream的存储的数据结构有关

代码如下:

 

private void button3_Click(object sender, EventArgs e)
        
{
            
if (FileCompare(this.textBox1.Text, this.textBox2.Text))
            
{
                MessageBox.Show(
"两个文件完全相同",this.Text,MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

            }

            
else
            
{
                MessageBox.Show(
"两个文件不相同",this.Text,MessageBoxButtons.OK ,
                    MessageBoxIcon.Information);
            
            }


        }

 

 

 

下面是实现FileCompare函数的代码:

 

 

 public bool FileCompare(string strPath_1, string strPath_2)
        
{
            
try
            
{
                
if (strPath_1 == strPath_2)
                
{

                    
return true;
                }


                
int file1byte = 0;
                
int file2byte = 0;

                
using (FileStream myStreamReader_1 = new FileStream(strPath_1, FileMode.Open),

                    myStreamReader_2 
= new FileStream(strPath_2, FileMode.Open)
                    )
                
{
                    
if (myStreamReader_1.Length != myStreamReader_2.Length)
                    
{
                        myStreamReader_1.Close();
                        myStreamReader_2.Close();
                        
return false;


                    }




                    
while (file1byte == file2byte)
                    
{

                        file1byte 
= myStreamReader_1.ReadByte();
                        file2byte 
= myStreamReader_2.ReadByte();


                    }

                }


                
return ((file1byte - file2byte) == 0);

            }


            
catch (Exception err)
            
{
                MessageBox.Show(err.Message, 
this.Text, MessageBoxButtons.OK, 
                    MessageBoxIcon.Information);
                
return false;
            }

        }

 

 如果把最后

MessageBox.Show(err.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

屏蔽掉,那么如果你对选取的文件无访问权限,也不会提示了!
                   

posted on 2008-07-26 22:40  C#gp  阅读(984)  评论(1编辑  收藏  举报