[VB.NET]文件操作

文件操作

实例说明

在本实例中,我们制作一个能够对文件进行操作的应用程序。程序运行后,可以新建一个文件和删除一个文件;同时可以显示文件的属性如文件类型、建立时间、更改时间和访问时间等。还可以更改这些属性。程序运行结果如图89-1所示。

图89-1 运行结果

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

技术要点

l 新建和删除文件

l 获得文件属性

l 更改文件属性

实现过程

■ 新建项目

打开Visual Studio.NET,选择"新建项目",在项目类型窗口中选择"Visual Basic项目",在模板窗口中选择"Windows应用程序",在名称域中输入"FileOperate",然后选择保存路径。单击"确认"。

■ 添加控件

在窗体上添加六个Button控件,一个GroupBox控件,并在GroupBox控件上放置八个Label控件。

■ 更改属性

将说明性的Label控件和Button控件的Text属性设置为和界面一致。其余属性保持不变。

■ 添加代码

Dim fileexam As System.IO.File

'新建文件

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

If fileexam.Exists("c:/abc.txt") = True Then

MsgBox("这个文件已经存在了!")

Exit Sub

End If

fileexam.Create("c:/abc.txt")

MsgBox("成功建立文件!")

Button3.Enabled = True

End Sub

'删除文件

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

If fileexam.Exists("c:/abc.txt") = True Then

fileexam.Delete("c:/abc.txt")

MsgBox("成功删除文件!")

Button3.Enabled = False

Else

MsgBox("这个文件不存在")

End If

End Sub

'得到文件的相关信息

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

Label1.Text = fileexam.GetAttributes("c:/abc.txt").ToString

Label2.Text = fileexam.GetCreationTime("c:/abc.txt").ToString

Label3.Text = fileexam.GetLastWriteTime("c:/abc.txt").ToString

Label4.Text = fileexam.GetLastAccessTime("c:/abc.txt").ToString

End Sub

'更改文件的属性(只读、隐藏、系统或文档)

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click

fileexam.SetAttributes("c:/abc.txt", IO.FileAttributes.ReadOnly)

End Sub

'更改文件的建立时间

Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click

fileexam.SetCreationTime("c:/abc.txt", Now)

End Sub

'更改最后访问时间

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

fileexam.SetLastAccessTime("c:/abc.txt", Now)

End Sub

■ 运行程序

单击菜单"调试|启动"或单击 图标运行程序。

小结

本实例可以取得文件的属性(如建立时间、属性、更改时间),并可以更改这些属性,而这些操作都是通过类(.NET)来实现的,并不需要调用API函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值