在C#中比较两个文件 [英] Comparing two files in C#
本文介绍了在C#中比较两个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较在C#中两个文件,看看他们是不同的。它们具有相同的文件名和它们的确切相同的尺寸时不同。我只是想知道是否有一个快速的方法来做到这一点,而无需手动去和读取文件。</ P>
感谢
解决方案
根据您正在寻找在多大程度上把它,你可以看看的 Diff.NET
下面是一个简单的文件比较功能:
//此方法接受两个字符串重新present两个文件
// 比较。返回0值表示的文件,这些文件的内容
// 是相同的。任何其他值一个返回值表示
//文件是不一样的。
私人布尔FileCompare(字符串文件1,字符串文件2)
{
INT file1byte;
INT file2byte;
的FileStream FS1;
的FileStream FS2;
//确定是否相同的文件被引用两次。
如果(文件1 ==文件2)
{
//返回true,表示该文件是相同的。
返回true;
}
//打开这两个文件。
FS1 =新的FileStream(文件1,FileMode.Open,FileAccess.Read);
FS2 =新的FileStream(文件2,FileMode.Open,FileAccess.Read);
//检查文件的大小。如果它们不相同,则文件
//是不一样的。
如果(fs1.Length!= fs2.Length)
{
//关闭文件
fs1.Close();
fs2.Close();
//返回false指示文件是不同的
返回false;
}
//读取和从每个文件比较一个字节,直到上
//不匹配设置的字节被发现,或直至年底
//文件1为止。
做
{
//读取每个文件一个字节。
file1byte = fs1.ReadByte();
file2byte = fs2.ReadByte();
}
而((file1byte == file2byte)及及(file1byte = -1)!);
//关闭文件。
fs1.Close();
fs2.Close();
//返回比较的成功。 file1byte是
//等于file2byte在这一点只有在文件
// 一样。
返程((file1byte - file2byte)== 0);
}
I want to compare two files in C# and see if they are different. They have the same file names and they are the exact same size when different. I was just wondering if there is a fast way to do this without having to manually go in and read the file.
Thanks
解决方案
Depending on how far you're looking to take it, you can take a look at Diff.NET
Here's a simple file comparison function:
// This method accepts two strings the represent two files to
// compare. A return value of 0 indicates that the contents of the files
// are the same. A return value of any other value indicates that the
// files are not the same.
private bool FileCompare(string file1, string file2)
{
int file1byte;
int file2byte;
FileStream fs1;
FileStream fs2;
// Determine if the same file was referenced two times.
if (file1 == file2)
{
// Return true to indicate that the files are the same.
return true;
}
// Open the two files.
fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read);
fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read);
// Check the file sizes. If they are not the same, the files
// are not the same.
if (fs1.Length != fs2.Length)
{
// Close the file
fs1.Close();
fs2.Close();
// Return false to indicate files are different
return false;
}
// Read and compare a byte from each file until either a
// non-matching set of bytes is found or until the end of
// file1 is reached.
do
{
// Read one byte from each file.
file1byte = fs1.ReadByte();
file2byte = fs2.ReadByte();
}
while ((file1byte == file2byte) && (file1byte != -1));
// Close the files.
fs1.Close();
fs2.Close();
// Return the success of the comparison. "file1byte" is
// equal to "file2byte" at this point only if the files are
// the same.
return ((file1byte - file2byte) == 0);
}
这篇关于在C#中比较两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文