本文介绍如何在 Visual C# 中创建 File-Compare 函数,并包含用于说明方法的代码示例。
原始产品版本: Visual C#
原始 KB 数: 320348
总结
本文介绍Microsoft .NET Framework 类库命名空间 System.IO
。
本分步文章演示如何比较两个文件,以查看其内容是否相同。 此比较查看两个文件的内容,而不是文件名、位置、日期、时间或其他属性。
此功能类似于基于 MS-DOS 的Fc.exe实用工具,这些实用工具包含在各种版本的 Microsoft Windows 和 Microsoft MS-DOS 以及某些开发工具中。
本文中介绍的示例代码执行字节字节比较,直到找到不匹配或到达文件的末尾。 该代码还执行两个简单的检查以提高比较效率:
- 如果两个文件引用都指向同一个文件,则两个文件必须相等。
- 如果两个文件的大小不相同,则两个文件不同。
创建示例
创建新的 Visual C# Windows 应用程序项目。 默认情况下,创建 Form1。
向窗体添加两个文本框控件。
向窗体添加命令按钮。
在 “视图” 菜单上,单击 “代码”。
将以下
using
语句添加到Form1
类:using System.IO;
将下列方法添加到
Form1
类:// 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); fs2 = new FileStream(file2, FileMode.Open); // 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); }
将以下代码粘贴到
Click
命令按钮的事件中:private void button1_Click(object sender, System.EventArgs e) { // Compare the two files that referenced in the textbox controls. if (FileCompare(this.textBox1.Text, this.textBox2.Text)) { MessageBox.Show("Files are equal."); } else { MessageBox.Show("Files are not equal."); } }
保存并运行示例。
在文本框中提供两个文件的完整路径,然后单击命令按钮。
参考
有关详细信息,请访问Microsoft网站 System.IO 命名空间。