windows创建文件C语言,在 C 中创建文件比较函数# - C# | Microsoft Docs

使用 Visual c # 创建文件比较函数

04/13/2020

本文内容

本文提供了有关如何在 Visual c # 中创建文件比较函数的信息,并包含用于解释这些方法的代码示例。

原始产品版本:  Visual C#

原始 KB 数:  320348

摘要

本文引用 Microsoft .NET Framework 类库命名空间 System.IO 。

本分步指南演示如何比较两个文件,以查看它们的内容是否相同。 此比较将查看两个文件的内容,而不是文件名、位置、日期、时间或其他属性。

此功能类似于基于 MS-DOS 的 Fc.exe 实用工具,它们包含在各种版本的 Microsoft Windows 和 Microsoft MS-DOS 以及一些开发工具中。

本文中描述的示例代码将执行逐字节的比较,直到发现不匹配或到达文件末尾为止。 该代码还执行两个简单的检查以提高比较效率:

如果两个文件引用指向同一个文件,则这两个文件必须相同。

如果两个文件的大小不同,则这两个文件不相同。

创建示例

创建新的 Visual c # Windows 应用程序项目。 默认情况下,创建 Form1。

向窗体中添加两个 textbox 控件。

向窗体中添加一个命令按钮。

在“视图”**** 菜单上,单击“代码”****。

将以下 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 命名空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值