说明:以下代码在Microsoft Visual Basic 2005 (简体中文版)中通过。
创建新项目:
在窗体上添加文本框2个:TextBox1,TextBox2
TextBox1 -- 用来编辑要写入的文本文件的内容,或显示打开的文本文件的内容
TextBox2 -- 用来输入要打开或要写入的文件名(包括盘符,路径)(例如:c:\123.txt)
在窗体上添加2个按钮:Button1,Button2
Button1 -- 写入文件
Button2 -- 打开文件
代码如下:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim w As New StreamWriter(TextBox2.Text)
w.Write(TextBox1.Text)
w.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim r As New StreamReader(TextBox2.Text)
Dim s As String
TextBox1.Text = ""
Do While r.Peek > -1 '是否到文件尾
s = r.ReadLine
' MessageBox.Show(r.Peek)
TextBox1.Text = TextBox1.Text & s & vbCrLf
Loop
r.Close()
End Sub
End Class
补充:你要把读出的数据赋值给一个变量,只要:声明一个变量为数值类型,然后只要读取一行就可以了,把这行数据经过转换成数值后赋给这个变量.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim fn As Integer
Dim str As String
str = ""
fn = FreeFile()
FileOpen(fn, "c:/test.txt", OpenMode.Input)
Input(fn, str)
MsgBox(str)
End Sub
学习中。